Merge commit 'a6759787c' into f-split-int

This commit is contained in:
Niko1221 committed 2026-10-17 21:49:11 +02:00
commit 80e6d91a63
45 files changed
+4797 -205

No files matched your search

+47
View File
@@ -360,6 +360,7 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP)
# reference is the whole point - a kernel checked against another copy of itself proves nothing.
add_library(strata_kernels STATIC src/kernels/cuda/dequant_s2.cu src/kernels/cuda/s2_gemv.cu
src/kernels/cuda/s_gemv.cu
src/kernels/cuda/s_gemv_pair.cu
src/kernels/cuda/s2_gemv_quads.cu
src/kernels/cuda/s2_gemv_fast.cu
src/kernels/cuda/router_top10.cu
@@ -428,6 +429,13 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP)
target_include_directories(qsa_prompt_attn_parity PRIVATE ${CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES})
target_link_libraries(qsa_prompt_attn_parity PRIVATE strata_kernels CUDA::cudart)
endif()
# PR #600: the Volta (sm_70) prompt attention's latency pipeline against the FP32 kernel it replaces. Only in the
# experimental sm_60/sm_70 build, where prompt_attn_v70_kernel is compiled in.
if(STRATA_BUILD_TESTS AND STRATA_ENABLE_CUDA AND STRATA_EXPERIMENTAL_SM60)
add_executable(qsa_prompt_attn_sm70_bench bench/qsa_prompt_attn_sm70_bench.cpp)
target_include_directories(qsa_prompt_attn_sm70_bench PRIVATE ${CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES})
target_link_libraries(qsa_prompt_attn_sm70_bench PRIVATE strata_kernels CUDA::cudart)
endif()
# #512: the top-k's active-block bound (Turing's dispatch, forced on any card by STRATA_TOPK_ACTIVE_ANY) against
# the capacity rule, selected ids bitwise
if(STRATA_BUILD_TESTS AND STRATA_ENABLE_CUDA)
@@ -687,6 +695,11 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP)
endif()
target_include_directories(strata_prefill PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include ${_strata_gpu_include_directories})
target_link_libraries(strata_prefill PUBLIC strata_engine ${_strata_gpu_blas_target} ${_strata_gpu_runtime_target})
if(STRATA_ENABLE_CUDA)
# v100/gdn-chunk: the chunked Volta GDN prompt recurrence. The dispatch (src/prefill/kernels.cu) is
# Volta-only (cc 7.0) and gated on STRATA_EXPERIMENTAL_SM60; the path itself stays opt-in (STRATA_GDN_CHUNK).
target_sources(strata_prefill PRIVATE src/prefill/gdn_chunk.cu)
endif()
if(STRATA_ENABLE_HIP AND STRATA_HIPBLASLT_AVAILABLE)
target_compile_definitions(strata_prefill PRIVATE STRATA_HIPBLASLT_AVAILABLE=1)
target_link_libraries(strata_prefill PRIVATE roc::hipblaslt)
@@ -1002,6 +1015,14 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP)
add_test(NAME gfx906_gdn_rec_head COMMAND gfx906_gdn_rec_head)
set_tests_properties(gfx906_gdn_rec_head PROPERTIES TIMEOUT 120)
endif()
if(STRATA_ENABLE_CUDA)
# the Volta prompt experts (gemm_iq_f16_grouped, STRATA_PF_WMMA) against a double reference; skipped below sm_70
add_executable(pf_wmma_parity src/kernels/pf_wmma_parity.cpp)
target_include_directories(pf_wmma_parity PRIVATE ${_strata_gpu_include_directories})
target_link_libraries(pf_wmma_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target})
add_test(NAME pf_wmma_parity COMMAND pf_wmma_parity)
set_tests_properties(pf_wmma_parity PROPERTIES SKIP_RETURN_CODE 77)
endif()
add_executable(shared_expert_parity src/kernels/shared_expert_parity.cpp)
target_include_directories(shared_expert_parity PRIVATE ${_strata_gpu_include_directories})
target_link_libraries(shared_expert_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target})
@@ -1036,6 +1057,22 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP)
target_link_libraries(gdn_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target})
add_test(NAME gdn_parity COMMAND gdn_parity --selftest)
# v100/gdn-chunk: the chunked GDN prompt recurrence vs the token recurrence and a host reference (GPU,
# synthetic, no model). The chunked path changes the summation order - FP32-level, not bit-exact - so the
# test asserts measured error bounds, and --selftest pins them.
if(STRATA_BUILD_TESTS AND STRATA_ENABLE_CUDA)
add_executable(gdn_chunk_parity src/kernels/gdn_chunk_parity.cpp)
target_include_directories(gdn_chunk_parity PRIVATE ${_strata_gpu_include_directories})
target_link_libraries(gdn_chunk_parity PRIVATE strata_prefill ${_strata_gpu_runtime_target})
add_test(NAME gdn_chunk_parity COMMAND gdn_chunk_parity --selftest)
set_tests_properties(gdn_chunk_parity PROPERTIES SKIP_RETURN_CODE 77)
# v100/gdn-chunk: the micro benchmark (CUDA events, real GDN shapes): chunked vs recurrent prompt path.
add_executable(gdn_chunk_bench bench/gdn_chunk_bench.cpp)
target_include_directories(gdn_chunk_bench PRIVATE ${_strata_gpu_include_directories})
target_link_libraries(gdn_chunk_bench PRIVATE strata_prefill ${_strata_gpu_runtime_target})
endif()
add_executable(s2_gemv_q8_parity src/kernels/s2_gemv_q8_parity.cpp)
target_include_directories(s2_gemv_q8_parity PRIVATE ${_strata_gpu_include_directories})
target_link_libraries(s2_gemv_q8_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target})
@@ -1143,6 +1180,16 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP)
target_link_libraries(bf16_gemv_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target})
add_test(NAME bf16_gemv_parity COMMAND bf16_gemv_parity --selftest)
# the V100 fusion work: every fused kernel against its unfused pipeline, bitwise, and the before/after
# CUDA-event timings at decode shapes (`--bench`). It is a .cu because it carries the unfused reference
# kernels it compares against.
if(STRATA_BUILD_TESTS AND STRATA_ENABLE_CUDA)
add_executable(fusions_parity bench/micro/fusions_parity.cu)
target_include_directories(fusions_parity PRIVATE ${_strata_gpu_include_directories})
target_link_libraries(fusions_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target})
add_test(NAME fusions_parity COMMAND fusions_parity)
endif()
add_executable(s_gemv_q8k_parity src/kernels/s_gemv_q8k_parity.cpp)
target_include_directories(s_gemv_q8k_parity PRIVATE ${_strata_gpu_include_directories})
target_link_libraries(s_gemv_q8k_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target})
+143
View File
@@ -0,0 +1,143 @@
// bench/gdn_chunk_bench.cpp - v100/gdn-chunk: the chunked GDN prompt recurrence against the token recurrence,
// real GDN geometry (S=128, 16 q/k heads, 48 v heads, C=10240), CUDA events.
//
// One call of `gdn_recurrence` per side (the whole prompt chunk for one GDN layer: conv output -> out norm),
// A/B'd with STRATA_GDN_CHUNK=0 / =1 so the dispatch, the tail and the norm are timed exactly as the engine
// runs them. The two paths are not bit-exact (the chunked one reorders the sums); the bench reports the max
// relative difference it saw so a silent divergence cannot hide behind a speedup.
//
// usage: gdn_chunk_bench [T ...] (default 1024 4096 8192)
#include "strata/prefill/kernels.hpp"
#include <cuda_runtime.h>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <vector>
namespace {
constexpr int S = 128, HV = 48, C = 10240;
void check(cudaError_t e, const char* what) {
if (e != cudaSuccess) {
std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(e));
std::exit(1);
}
}
struct Rng {
uint64_t s = 12345;
float uni() {
s = s * 6364136223846793005ULL + 1442695040888963407ULL;
return (float) ((s >> 40) * (1.0 / 16777216.0));
}
};
float timed(const char* mode, const char* warp, float* st, float* st0, float* h, float* g, float* b, float* z,
float* ga, float* y, uint16_t* y16, int64_t T, int iters) {
setenv("STRATA_GDN_CHUNK", mode, 1);
setenv("STRATA_GDN_REC_WARP", warp, 1);
cudaEvent_t e0, e1;
check(cudaEventCreate(&e0), "event");
check(cudaEventCreate(&e1), "event");
check(cudaMemcpy(st, st0, (size_t) S * HV * S * 4, cudaMemcpyDeviceToDevice), "reset");
strata::prefill::gdn_recurrence(st, h, g, b, z, ga, 1e-5f, y, y16, T, nullptr);
check(cudaDeviceSynchronize(), "warmup");
check(cudaEventRecord(e0), "record");
for (int i = 0; i < iters; ++i) {
check(cudaMemcpy(st, st0, (size_t) S * HV * S * 4, cudaMemcpyDeviceToDevice), "reset");
strata::prefill::gdn_recurrence(st, h, g, b, z, ga, 1e-5f, y, y16, T, nullptr);
}
check(cudaEventRecord(e1), "record");
check(cudaEventSynchronize(e1), "sync");
float ms = 0;
check(cudaEventElapsedTime(&ms, e0, e1), "elapsed");
cudaEventDestroy(e0);
cudaEventDestroy(e1);
return ms / iters;
}
} // namespace
int main(int argc, char** argv) {
std::vector<int64_t> ts;
for (int i = 1; i < argc; ++i) ts.push_back(std::atoll(argv[i]));
if (ts.empty()) ts = {1024, 4096, 8192};
int64_t tmax = 0;
for (int64_t t : ts) tmax = t > tmax ? t : tmax;
int dev = 0;
cudaDeviceProp p{};
check(cudaGetDevice(&dev), "device");
check(cudaGetDeviceProperties(&p, dev), "props");
const int cc = p.major * 10 + p.minor;
std::printf("%s (cc %d) GDN prompt recurrence: chunked vs token-by-token\n", p.name, cc);
Rng rng;
const size_t n_h = (size_t) tmax * C, n_y = (size_t) tmax * HV * S, n_g = (size_t) tmax * HV;
float *d_h, *d_y, *d_z, *d_g, *d_b, *d_ga, *d_st, *d_st0;
uint16_t* d_y16;
check(cudaMalloc(&d_h, n_h * 4), "malloc");
check(cudaMalloc(&d_y, n_y * 4), "malloc");
check(cudaMalloc(&d_z, n_y * 4), "malloc");
check(cudaMalloc(&d_g, n_g * 4), "malloc");
check(cudaMalloc(&d_b, n_g * 4), "malloc");
check(cudaMalloc(&d_ga, S * 4), "malloc");
check(cudaMalloc(&d_st, (size_t) S * HV * S * 4), "malloc");
check(cudaMalloc(&d_st0, (size_t) S * HV * S * 4), "malloc");
check(cudaMalloc(&d_y16, n_y * 2), "malloc");
std::vector<float> tmp((size_t) tmax * C);
for (size_t i = 0; i < tmp.size(); ++i) tmp[i] = rng.uni() - 0.5f;
// q/k rows are L2-normalised rows (as gdn_conv leaves them); v rows stay O(1). A degenerate near-zero
// v would make the out-norm amplify rounding noise by 1/sqrt(eps) and the diff column meaningless.
for (int64_t t = 0; t < tmax; ++t)
for (int row = 0; row < 2 * 16; ++row) {
float* r = tmp.data() + (size_t) t * C + row * S;
double ss = 0;
for (int i = 0; i < S; ++i) ss += (double) r[i] * r[i];
const float nrm = (float) (1.0 / std::sqrt(ss + 1e-5));
for (int i = 0; i < S; ++i) r[i] *= nrm;
}
check(cudaMemcpy(d_h, tmp.data(), n_h * 4, cudaMemcpyHostToDevice), "H2D");
tmp.resize(n_g);
for (size_t i = 0; i < n_g; ++i) tmp[i] = -0.02f - 0.3f * rng.uni();
check(cudaMemcpy(d_g, tmp.data(), n_g * 4, cudaMemcpyHostToDevice), "H2D");
for (size_t i = 0; i < n_g; ++i) tmp[i] = 1.0f / (1.0f + std::exp(-(4.0f * rng.uni() - 2.0f)));
check(cudaMemcpy(d_b, tmp.data(), n_g * 4, cudaMemcpyHostToDevice), "H2D");
tmp.resize(n_y);
for (size_t i = 0; i < n_y; ++i) tmp[i] = 2.0f * rng.uni() - 1.0f;
check(cudaMemcpy(d_z, tmp.data(), n_y * 4, cudaMemcpyHostToDevice), "H2D");
tmp.resize(S);
for (int i = 0; i < S; ++i) tmp[i] = 0.5f + 2.0f * rng.uni();
check(cudaMemcpy(d_ga, tmp.data(), S * 4, cudaMemcpyHostToDevice), "H2D");
tmp.resize((size_t) S * HV * S);
for (size_t i = 0; i < tmp.size(); ++i) tmp[i] = 0.1f * (rng.uni() - 0.5f);
check(cudaMemcpy(d_st0, tmp.data(), tmp.size() * 4, cudaMemcpyHostToDevice), "H2D");
std::printf("%8s %12s %12s %12s %12s %12s %s\n", "T", "pipe(rec)", "warp(rec)", "fast(rec)", "chunk FMA",
"chunk wmma", "max abs diff vs pipe");
for (int64_t T : ts) {
const int iters = T >= 4096 ? 5 : 20;
const float rec = timed("0", "0", d_st, d_st0, d_h, d_g, d_b, d_z, d_ga, d_y, d_y16, T, iters);
std::vector<float> y0((size_t) T * HV * S);
check(cudaMemcpy(y0.data(), d_y, y0.size() * 4, cudaMemcpyDeviceToHost), "D2H");
const float wrp = timed("0", "1", d_st, d_st0, d_h, d_g, d_b, d_z, d_ga, d_y, d_y16, T, iters);
const float fst = timed("0", "2", d_st, d_st0, d_h, d_g, d_b, d_z, d_ga, d_y, d_y16, T, iters);
const float fma = timed("2", "0", d_st, d_st0, d_h, d_g, d_b, d_z, d_ga, d_y, d_y16, T, iters);
const float ch = timed("1", "0", d_st, d_st0, d_h, d_g, d_b, d_z, d_ga, d_y, d_y16, T, iters);
std::vector<float> y1((size_t) T * HV * S);
check(cudaMemcpy(y1.data(), d_y, y1.size() * 4, cudaMemcpyDeviceToHost), "D2H");
double absd = 0;
for (size_t i = 0; i < y0.size(); ++i) {
const double d = std::fabs((double) y1[i] - (double) y0[i]);
if (d > absd) absd = d;
}
std::printf("%8lld %11.3fms %11.3fms %11.3fms %11.3fms %11.3fms %.2e (wmma vs pipe)\n", (long long) T,
rec, wrp, fst, fma, ch, absd);
}
return 0;
}
+424
View File
@@ -0,0 +1,424 @@
// src/kernels/fusions_parity.cpp - the V100 fusion work against its own unfused pipeline, BITWISE, plus
// the before/after kernel timings (CUDA events).
//
// build/fusions_parity every bitwise check below; exit 1 on any difference
// build/fusions_parity --bench fused vs unfused kernel times at decode shapes (M=1 and M=8)
//
// WHAT IS CHECKED (synthetic data, GPU, no model):
// 1. `swilu_quantize_q8_0` / `_scaled` against `swiglu` + `quantize_q8_0` / `_scaled` - the S2 expert
// path's intermediate. Products, q8 bytes and the fp32 scales all bitwise.
// 2. `swilu_quantize_q8_0` / `_q8_K` with the LEGACY silu against `shared_expert`'s swiglu kernel +
// `quantize_q8_0` / `quantize_q8_K`.
// 3. `quantize_act_images` against the three standalone quantizers (q8_0 bytes, q8_K bytes, bf16 bits).
// 4. `bf16_gemv_pair` against two `bf16_gemv_split(32)` calls (the warp accumulation it replicates).
#include "strata/kernels/bf16_gemv.hpp"
#include "strata/kernels/bf16_bits.hpp"
#include "strata/kernels/elementwise.hpp"
#include "strata/kernels/f16_bits.hpp"
#include "strata/kernels/quantize_act.hpp"
#include "strata/kernels/s_gemv.hpp"
#include <cuda_runtime.h>
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <functional>
#include <random>
#include <string>
#include <vector>
namespace k = strata::kernels;
namespace {
int g_fail = 0;
void ck(cudaError_t e, const char* w) {
if (e != cudaSuccess) { std::fprintf(stderr, "%s: %s\n", w, cudaGetErrorString(e)); std::exit(2); }
}
template <typename T> T* dalloc(size_t n) {
T* p = nullptr;
ck(cudaMalloc(&p, n * sizeof(T)), "malloc");
ck(cudaMemset(p, 0, n * sizeof(T)), "memset");
return p;
}
template <typename T> void up(T* d, const std::vector<T>& h) {
ck(cudaMemcpy(d, h.data(), h.size() * sizeof(T), cudaMemcpyHostToDevice), "h2d");
}
template <typename T> std::vector<T> down(const T* d, size_t n) {
std::vector<T> h(n);
ck(cudaMemcpy(h.data(), d, n * sizeof(T), cudaMemcpyDeviceToHost), "d2h");
return h;
}
void report(const char* name, bool ok) {
std::printf(" %-52s %s\n", name, ok ? "bitwise identical" : "DIFFERS");
if (!ok) ++g_fail;
}
// the `gemv` dispatch `shared_expert`'s lambda uses (defined later; declared for `run_bench`)
void gemv_dispatch(const k::SForm& f, const uint8_t* codes, const float* scales, const float* off,
const uint8_t* x80, const uint8_t* x8k, float* y, long long n_in, long long n_out,
void* stream);
// ---- the unfused SwiGLU references, one thread per element (the shapes the standalone kernels had) ----
__global__ void swilu_legacy_kernel(const float* g, const float* u, float* out, int n) {
const int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i >= n) return;
const double x = (double) g[i];
out[i] = (float) (x / (1.0 + exp(-x))) * u[i];
}
__global__ void swilu_fast_kernel(const float* g, const float* u, float* out, int n) {
const int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i >= n) return;
out[i] = (g[i] / (1.0f + __expf(-g[i]))) * u[i];
}
__global__ void swilu_native_kernel(const float* g, const float* u, float* out, int n) {
const int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i >= n) return;
out[i] = __fdividef(g[i], 1.0f + __expf(-g[i])) * u[i];
}
void fill_pairs(std::vector<float>& g, std::vector<float>& u, unsigned seed) {
std::mt19937 rng(seed);
std::uniform_real_distribution<float> gv(-6.0f, 6.0f), uv(-3.0f, 3.0f);
for (size_t i = 0; i < g.size(); ++i) { g[i] = gv(rng); u[i] = uv(rng); }
}
void check_swilu_quantize(int kind, bool scaled, const char* name) {
const long long n = 640 * 4; // FF x a few hits, multiple of 256
std::vector<float> hg(n), hu(n);
fill_pairs(hg, hu, 7u + (unsigned) kind * 13 + (unsigned) scaled);
float *dg = dalloc<float>(n), *du = dalloc<float>(n), *dfused = dalloc<float>(n), *dref = dalloc<float>(n);
up(dg, hg); up(du, hu);
const size_t nb80 = (size_t) (n / 32);
uint8_t* db80 = dalloc<uint8_t>(nb80 * 34 + 256);
uint8_t* db80r = dalloc<uint8_t>(nb80 * 34 + 256);
float* ds = dalloc<float>(nb80 + 16);
float* dsr = dalloc<float>(nb80 + 16);
// fused
if (scaled) k::swilu_quantize_q8_0_scaled(dg, du, dfused, n, kind, db80, ds, nullptr);
else k::swilu_quantize_q8_0(dg, du, dfused, n, kind, db80, nullptr);
// unfused: standalone swilu then quantize
const int blocks = (int) ((n + 127) / 128);
if (kind == 0) swilu_legacy_kernel<<<blocks, 128>>>(dg, du, dref, (int) n);
else swilu_fast_kernel<<<blocks, 128>>>(dg, du, dref, (int) n);
ck(cudaGetLastError(), "swilu ref");
if (scaled) k::quantize_q8_0_scaled(dref, db80r, dsr, n, nullptr);
else k::quantize_q8_0(dref, db80r, n, nullptr);
ck(cudaDeviceSynchronize(), "sync");
const std::vector<float> p1 = down(dfused, n), p2 = down(dref, n);
const std::vector<uint8_t> q1 = down(db80, nb80 * 34), q2 = down(db80r, nb80 * 34);
bool ok = std::memcmp(p1.data(), p2.data(), n * sizeof(float)) == 0 &&
std::memcmp(q1.data(), q2.data(), nb80 * 34) == 0;
if (scaled) {
const std::vector<float> s1 = down(ds, nb80), s2 = down(dsr, nb80);
ok = ok && std::memcmp(s1.data(), s2.data(), nb80 * sizeof(float)) == 0;
}
report(name, ok);
cudaFree(dg); cudaFree(du); cudaFree(dfused); cudaFree(dref); cudaFree(db80); cudaFree(db80r);
cudaFree(ds); cudaFree(dsr);
}
void check_swilu_quantize_q8_K() {
const long long n = 256 * 3;
std::vector<float> hg(n), hu(n);
fill_pairs(hg, hu, 99u);
float *dg = dalloc<float>(n), *du = dalloc<float>(n), *df = dalloc<float>(n), *dr = dalloc<float>(n);
up(dg, hg); up(du, hu);
const size_t nbK = (size_t) (n / 256);
uint8_t* dK = dalloc<uint8_t>(nbK * 292 + 256);
uint8_t* dKr = dalloc<uint8_t>(nbK * 292 + 256);
k::swilu_quantize_q8_K(dg, du, df, n, 0, dK, nullptr);
const int blocks = (int) ((n + 127) / 128);
swilu_legacy_kernel<<<blocks, 128>>>(dg, du, dr, (int) n);
k::quantize_q8_K(dr, dKr, n, nullptr);
ck(cudaDeviceSynchronize(), "sync");
bool ok = down(df, n) == down(dr, n) && down(dK, nbK * 292) == down(dKr, nbK * 292);
report("swilu_quantize_q8_K (legacy silu)", ok);
cudaFree(dg); cudaFree(du); cudaFree(df); cudaFree(dr); cudaFree(dK); cudaFree(dKr);
}
void check_images() {
const long long n = 2560;
std::vector<float> hx(n);
std::mt19937 rng(4u);
std::uniform_real_distribution<float> d(-4.0f, 4.0f);
for (auto& v : hx) v = d(rng);
float* dx = dalloc<float>(n);
up(dx, hx);
const size_t nb80 = (size_t) (n / 32), nbK = (size_t) (n / 256);
uint8_t* i80 = dalloc<uint8_t>(nb80 * 34 + 256);
uint8_t* iK = dalloc<uint8_t>(nbK * 292 + 256);
uint16_t* i16 = dalloc<uint16_t>(n + 8);
uint8_t* r80 = dalloc<uint8_t>(nb80 * 34 + 256);
uint8_t* rK = dalloc<uint8_t>(nbK * 292 + 256);
k::quantize_act_images(dx, n, i80, iK, i16, nullptr);
k::quantize_q8_0(dx, r80, n, nullptr);
k::quantize_q8_K(dx, rK, n, nullptr);
ck(cudaDeviceSynchronize(), "sync");
// the standalone bf16 conversion is `bf16_from_f32` per element (`f32_to_bf16_bulk`)
std::vector<uint16_t> hb(n);
for (long long i = 0; i < n; ++i) hb[(size_t) i] = k::bf16_from_f32(hx[(size_t) i]);
const std::vector<uint16_t> got16 = down(i16, n);
report("quantize_act_images (q8_0 + q8_K + bf16)",
down(i80, nb80 * 34) == down(r80, nb80 * 34) && down(iK, nbK * 292) == down(rK, nbK * 292) &&
std::memcmp(got16.data(), hb.data(), n * sizeof(uint16_t)) == 0);
cudaFree(dx); cudaFree(i80); cudaFree(iK); cudaFree(i16); cudaFree(r80); cudaFree(rK);
}
void check_pair() {
const long long n_in = 2560, n1 = 48, n2 = 48; // ssm_alpha / ssm_beta shapes
std::vector<uint16_t> hx(n_in), hw1(n_in * n1), hw2(n_in * n2);
std::mt19937 rng(11u);
std::uniform_real_distribution<float> d(-2.0f, 2.0f);
auto put = [&](std::vector<uint16_t>& v) {
for (auto& t : v) t = k::bf16_from_f32(d(rng));
};
put(hx); put(hw1); put(hw2);
uint16_t *dx = dalloc<uint16_t>(n_in), *dw1 = dalloc<uint16_t>(n_in * n1), *dw2 = dalloc<uint16_t>(n_in * n2);
up(dx, hx); up(dw1, hw1); up(dw2, hw2);
float *dy1 = dalloc<float>(n1 + 8), *dy2 = dalloc<float>(n2 + 8), *dr1 = dalloc<float>(n1 + 8),
*dr2 = dalloc<float>(n2 + 8);
k::bf16_gemv_pair(dx, dw1, dy1, n1, dw2, dy2, n2, n_in, nullptr);
k::bf16_gemv_split(dx, dw1, dr1, n_in, n1, 32, nullptr);
k::bf16_gemv_split(dx, dw2, dr2, n_in, n2, 32, nullptr);
ck(cudaDeviceSynchronize(), "sync");
report("bf16_gemv_pair vs 2x bf16_gemv_split(32)",
down(dy1, n1) == down(dr1, n1) && down(dy2, n2) == down(dr2, n2));
cudaFree(dx); cudaFree(dw1); cudaFree(dw2); cudaFree(dy1); cudaFree(dy2); cudaFree(dr1); cudaFree(dr2);
}
// ---- micro bench: fused vs unfused kernel time at decode shapes, CUDA events -------------------------
//
// The decode geometry is the model's: n_embd 2560, FF 640 for the experts (H/FF from `cpu/expert.hpp`).
// M = 1 is the single-token decode; M = 8 runs the M=8 pair shapes (8 columns of the same weights).
float timed(cudaStream_t s, const std::function<void()>& f, int reps) {
cudaEvent_t a, b;
ck(cudaEventCreate(&a), "ev"); ck(cudaEventCreate(&b), "ev");
f(); ck(cudaStreamSynchronize(s), "sync"); // warmup
ck(cudaEventRecord(a, s), "rec");
for (int i = 0; i < reps; ++i) f();
ck(cudaEventRecord(b, s), "rec");
ck(cudaEventSynchronize(b), "sync");
float ms = 0.0f;
ck(cudaEventElapsedTime(&ms, a, b), "elapsed");
cudaEventDestroy(a); cudaEventDestroy(b);
return ms / reps;
}
void bench_pair(const char* what, const std::function<void()>& before, const std::function<void()>& after,
int reps) {
cudaStream_t s = nullptr;
const float t0 = timed(s, before, reps), t1 = timed(s, after, reps);
std::printf(" %-44s unfused %8.1f us fused %8.1f us %+.1f%%\n", what, t0 * 1e3f, t1 * 1e3f,
(t1 / t0 - 1.0f) * 100.0f);
}
void run_bench() {
std::printf("\nfusions bench: decode shapes (n_embd 2560, FF 640), CUDA events, %s\n",
"stream = default, 200 reps");
const int reps = 200;
for (int m : {1, 8}) {
const long long pairs = (long long) 640 * m; // one expert hit's rows x tokens
std::vector<float> hg(pairs), hu(pairs);
fill_pairs(hg, hu, 5u + (unsigned) m);
float *dg = dalloc<float>(pairs), *du = dalloc<float>(pairs), *dout = dalloc<float>(pairs);
up(dg, hg); up(du, hu);
const size_t nb = (size_t) (pairs / 32);
uint8_t* d80 = dalloc<uint8_t>(nb * 34 + 256);
float* ds = dalloc<float>(nb + 16);
char label[96];
std::snprintf(label, sizeof label, "expert intermediate M=%d (swilu + q8_0)", m);
bench_pair(label,
[&] {
const int blocks = (int) ((pairs + 127) / 128);
swilu_fast_kernel<<<blocks, 128>>>(dg, du, dout, (int) pairs);
k::quantize_q8_0(dout, d80, pairs, nullptr);
},
[&] { k::swilu_quantize_q8_0(dg, du, dout, pairs, 1, d80, nullptr); }, reps);
cudaFree(dg); cudaFree(du); cudaFree(dout); cudaFree(d80); cudaFree(ds);
}
{
const long long n = 2560;
std::vector<float> hx(n);
std::mt19937 rng(21u);
std::uniform_real_distribution<float> d(-4.0f, 4.0f);
for (auto& v : hx) v = d(rng);
float* dx = dalloc<float>(n);
up(dx, hx);
const size_t nb80 = (size_t) (n / 32), nbK = (size_t) (n / 256);
uint8_t* o80 = dalloc<uint8_t>(nb80 * 34 + 256);
uint8_t* oK = dalloc<uint8_t>(nbK * 292 + 256);
uint16_t* o16 = dalloc<uint16_t>(n + 8);
bench_pair("layer activation images (q8_0 + q8_K + bf16)",
[&] {
k::quantize_q8_0(dx, o80, n, nullptr);
k::quantize_q8_K(dx, oK, n, nullptr);
k::f32_to_bf16_bulk(dx, o16, n, nullptr);
},
[&] { k::quantize_act_images(dx, n, o80, oK, o16, nullptr); }, reps);
cudaFree(dx); cudaFree(o80); cudaFree(oK); cudaFree(o16);
}
{
// (a) gate/up dual GEMV + SwiGLU: one kernel vs gemv(gate) + gemv(up) + swilu, shared-expert shapes
const long long n_in = 2560, n_out = 640;
const long long n_groups = n_in / 64;
std::vector<uint8_t> hcg((size_t) n_out * n_in / 2), hcu((size_t) n_out * n_in / 2);
std::vector<float> hsg((size_t) n_out * n_groups), hsu((size_t) n_out * n_groups);
std::vector<float> hog((size_t) n_out * n_groups), hou((size_t) n_out * n_groups);
std::vector<float> hx(n_in);
std::mt19937 rng(55u);
for (auto& v : hcg) v = (uint8_t) rng();
for (auto& v : hcu) v = (uint8_t) rng();
std::uniform_real_distribution<float> sc(1e-3f, 3e-2f), xv(-4.0f, 4.0f), ov(-1e-2f, 1e-2f);
for (auto& v : hsg) v = sc(rng);
for (auto& v : hsu) v = sc(rng);
for (auto& v : hog) v = ov(rng);
for (auto& v : hou) v = ov(rng);
for (auto& v : hx) v = xv(rng);
float* dx2 = dalloc<float>(n_in);
up(dx2, hx);
uint8_t* dx80 = dalloc<uint8_t>((size_t) (n_in / 32) * 34 + 256);
k::quantize_q8_0(dx2, dx80, n_in, nullptr);
uint8_t *dcg = dalloc<uint8_t>(hcg.size()), *dcu = dalloc<uint8_t>(hcu.size());
float *dsg = dalloc<float>(hsg.size()), *dsu = dalloc<float>(hsu.size());
float *dog = dalloc<float>(hog.size()), *dou = dalloc<float>(hou.size());
up(dcg, hcg); up(dcu, hcu); up(dsg, hsg); up(dsu, hsu); up(dog, hog); up(dou, hou);
float *d_gate = dalloc<float>(n_out + 8), *d_up = dalloc<float>(n_out + 8), *d_pair = dalloc<float>(n_out + 8);
const k::SForm fg{4, -8, 64, k::Codebook::Affine, true, 0};
const k::SForm fu{4, -8, 64, k::Codebook::Affine, true, 0};
bench_pair("dual GEMV + swilu (gate,up) FF=640",
[&] {
gemv_dispatch(fg, dcg, dsg, dog, dx80, nullptr, d_gate, n_in, n_out, nullptr);
gemv_dispatch(fu, dcu, dsu, dou, dx80, nullptr, d_up, n_in, n_out, nullptr);
const int bl = (int) ((n_out + 127) / 128);
swilu_legacy_kernel<<<bl, 128>>>(d_gate, d_up, d_pair, (int) n_out);
},
[&] {
k::s_gemv_pair_silu(dx80, nullptr, fg, dcg, dsg, dog, fu, dcu, dsu, dou, d_pair,
n_in, n_out, 32, 0, nullptr);
}, reps);
cudaFree(dx2); cudaFree(dx80); cudaFree(dcg); cudaFree(dcu); cudaFree(dsg); cudaFree(dsu);
cudaFree(dog); cudaFree(dou); cudaFree(d_gate); cudaFree(d_up); cudaFree(d_pair);
}
for (int m : {1, 8}) {
const long long n_in = 2560, n1 = 48, n2 = 48;
std::vector<uint16_t> hx(n_in), hw1(n_in * n1), hw2(n_in * n2);
std::mt19937 rng(31u + (unsigned) m);
std::uniform_real_distribution<float> d(-2.0f, 2.0f);
auto put = [&](std::vector<uint16_t>& v) { for (auto& t : v) t = k::bf16_from_f32(d(rng)); };
put(hx); put(hw1); put(hw2);
uint16_t *dx = dalloc<uint16_t>(n_in), *dw1 = dalloc<uint16_t>(n_in * n1), *dw2 = dalloc<uint16_t>(n_in * n2);
up(dx, hx); up(dw1, hw1); up(dw2, hw2);
float *dy1 = dalloc<float>(n1 + 8), *dy2 = dalloc<float>(n2 + 8);
char label[96];
std::snprintf(label, sizeof label, "bf16 pair (alpha,beta) M=%d", m);
bench_pair(label,
[&] {
k::bf16_gemv_split(dx, dw1, dy1, n_in, n1, 32, nullptr);
k::bf16_gemv_split(dx, dw2, dy2, n_in, n2, 32, nullptr);
},
[&] { k::bf16_gemv_pair(dx, dw1, dy1, n1, dw2, dy2, n2, n_in, nullptr); }, reps);
cudaFree(dx); cudaFree(dw1); cudaFree(dw2); cudaFree(dy1); cudaFree(dy2);
}
}
// ---- (a) the gate/up dual GEMV + SwiGLU kernel against its unfused pipeline, bitwise ----------------
// The unfused pipeline is the one `shared_expert` ran: a standalone GEMV per projection (dispatching the
// same way its `gemv` lambda does) then the standalone SwiGLU kernel. Both silu kinds are checked.
void gemv_dispatch(const k::SForm& f, const uint8_t* codes, const float* scales, const float* off,
const uint8_t* x80, const uint8_t* x8k, float* y, long long n_in, long long n_out,
void* stream) {
if (f.code_bits == 2) {
std::fprintf(stderr, "gemv_dispatch: code_bits 2 goes through s2_gemv_q8 - not exercised here\n");
std::exit(2);
}
if (f.act_kind == 1) k::s_gemv_q8k_split(x8k, codes, scales, off, y, n_in, n_out, f, stream);
else k::s_gemv_q8_0_split(x80, codes, scales, off, y, n_in, n_out, f, stream);
}
void check_dual_gemv(int swilu_kind, const char* name) {
const long long n_in = 2560, n_out = 128;
const long long n_groups = n_in / 64;
std::vector<uint8_t> hcg((size_t) n_out * n_in / 2), hcu((size_t) n_out * n_in / 2); // S4 codes
std::vector<float> hsg((size_t) n_out * n_groups), hsu((size_t) n_out * n_groups);
std::vector<float> hog((size_t) n_out * n_groups), hou((size_t) n_out * n_groups);
std::vector<float> hx(n_in);
std::mt19937 rng(77u + (unsigned) swilu_kind);
for (auto& v : hcg) v = (uint8_t) rng();
for (auto& v : hcu) v = (uint8_t) rng();
std::uniform_real_distribution<float> sc(1e-3f, 3e-2f), xv(-4.0f, 4.0f), ov(-1e-2f, 1e-2f);
for (auto& v : hsg) v = sc(rng);
for (auto& v : hsu) v = sc(rng);
for (auto& v : hog) v = ov(rng);
for (auto& v : hou) v = ov(rng);
for (auto& v : hx) v = xv(rng);
// Q8_0 activation image of x (both sides use it)
const size_t nb80 = (size_t) (n_in / 32);
std::vector<uint8_t> hx80(nb80 * 34 + 256);
uint8_t* dx80 = dalloc<uint8_t>(hx80.size());
float* dx = dalloc<float>(n_in);
up(dx, hx);
k::quantize_q8_0(dx, dx80, n_in, nullptr);
ck(cudaDeviceSynchronize(), "sync");
uint8_t *dcg = dalloc<uint8_t>(hcg.size()), *dcu = dalloc<uint8_t>(hcu.size());
float *dsg = dalloc<float>(hsg.size()), *dsu = dalloc<float>(hsu.size());
float *dog = dalloc<float>(hog.size()), *dou = dalloc<float>(hou.size());
up(dcg, hcg); up(dcu, hcu); up(dsg, hsg); up(dsu, hsu); up(dog, hog); up(dou, hou);
float* d_pair = dalloc<float>(n_out + 8);
float* d_gate = dalloc<float>(n_out + 8), *d_up = dalloc<float>(n_out + 8), *d_ref = dalloc<float>(n_out + 8);
const k::SForm fg{4, -8, 64, k::Codebook::Affine, true, 0};
const k::SForm fu{4, -8, 64, k::Codebook::Affine, true, 0};
const bool ok_launch = k::s_gemv_pair_silu(dx80, nullptr, fg, dcg, dsg, dog, fu, dcu, dsu, dou,
d_pair, n_in, n_out, 32, swilu_kind, nullptr);
// unfused: the same two GEMVs the `gemv` lambda would run, then the standalone swilu
gemv_dispatch(fg, dcg, dsg, dog, dx80, nullptr, d_gate, n_in, n_out, nullptr);
gemv_dispatch(fu, dcu, dsu, dou, dx80, nullptr, d_up, n_in, n_out, nullptr);
const int blocks = (int) ((n_out + 127) / 128);
if (swilu_kind == 0) swilu_legacy_kernel<<<blocks, 128>>>(d_gate, d_up, d_ref, (int) n_out);
else if (swilu_kind == 1) swilu_fast_kernel<<<blocks, 128>>>(d_gate, d_up, d_ref, (int) n_out);
else swilu_native_kernel<<<blocks, 128>>>(d_gate, d_up, d_ref, (int) n_out);
ck(cudaGetLastError(), "swilu ref");
ck(cudaDeviceSynchronize(), "sync");
report(name, ok_launch && down(d_pair, n_out) == down(d_ref, n_out));
cudaFree(dx80); cudaFree(dx); cudaFree(dcg); cudaFree(dcu); cudaFree(dsg); cudaFree(dsu);
cudaFree(dog); cudaFree(dou); cudaFree(d_pair); cudaFree(d_gate); cudaFree(d_up); cudaFree(d_ref);
}
} // namespace
int main(int argc, char** argv) {
bool bench = false;
for (int i = 1; i < argc; ++i)
if (std::string(argv[i]) == "--bench") bench = true;
else { std::fprintf(stderr, "usage: fusions_parity [--bench]\n"); return 2; }
std::printf("fusions_parity: V100 fusions vs their unfused pipelines, bitwise\n");
check_swilu_quantize(1, false, "swilu_quantize_q8_0 (fast silu, expert path)");
check_swilu_quantize(1, true, "swilu_quantize_q8_0_scaled (fast silu, expert path)");
check_swilu_quantize(0, false, "swilu_quantize_q8_0 (legacy silu, shared expert)");
check_swilu_quantize_q8_K();
check_images();
check_pair();
check_dual_gemv(0, "s_gemv_pair_silu (legacy silu) vs gemv+gemv+swilu");
check_dual_gemv(1, "s_gemv_pair_silu (fast silu) vs gemv+gemv+swilu");
check_dual_gemv(2, "s_gemv_pair_silu (native silu) vs gemv+gemv+swilu");
if (bench) run_bench();
std::printf(g_fail ? "fusions_parity: %d failures\n" : "fusions_parity: 0 failures\n", g_fail);
return g_fail ? 1 : 0;
}
+198
View File
@@ -0,0 +1,198 @@
// bench/qsa_prompt_attn_sm70_bench.cpp - the Volta (sm_70) prompt attention against the FP32 kernel it replaces.
//
// Same synthetic pools and prompt-shaped selections as src/kernels/qsa_prompt_attn_parity.cpp (GPU, no model), but
// timing is the point: for each KV format (int8, fp16) and a sweep of query counts it times
// `qsa_decode_attn_batch` (the FP32 fallback, in batches of 32 as prefill.cpp calls it) against
// `qsa_prompt_attn_batch` with CUDA events, and reports the output difference. Run it on one card:
// flock /tmp/opencode/gpu.lock -c 'CUDA_VISIBLE_DEVICES=0 ./qsa_prompt_attn_sm70_bench [ctx=32768] [nq=2048] [reps=10]'
#include "strata/kernels/qsa.hpp"
#include "strata/kernels/qsa_decode_attn.hpp"
#include "strata/kernels/qsa_prompt_attn.hpp"
#include <cuda_fp16.h>
#include <cuda_runtime.h>
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <functional>
#include <random>
#include <vector>
namespace k = strata::kernels;
namespace {
void ck(cudaError_t e, const char* w) {
if (e != cudaSuccess) { std::fprintf(stderr, "%s: %s\n", w, cudaGetErrorString(e)); std::exit(2); }
}
template <typename T> T* up(const std::vector<T>& h) {
T* d = nullptr;
ck(cudaMalloc(&d, h.size() * sizeof(T) + 64), "malloc");
ck(cudaMemcpy(d, h.data(), h.size() * sizeof(T), cudaMemcpyHostToDevice), "upload");
return d;
}
uint16_t f2h(float f) { __half h = __float2half(f); return *reinterpret_cast<uint16_t*>(&h); }
// one synthetic prompt: the widest selection the shape has (2,051 cells at 32K), a recent window plus older cells
// that drift slowly from query to query, as qsa_prompt_attn_parity builds them. fmt 1 int8 KV, 0 fp16 KV,
// 2 hybrid K8V4 (int8 K, q4_0 V - the Q2_0 engine's pools)
void build(int fmt, int64_t ctx, int64_t nq, std::vector<int8_t>& kq, std::vector<int8_t>& vq, std::vector<uint16_t>& ks,
std::vector<uint16_t>& vs, std::vector<uint16_t>& kh, std::vector<uint16_t>& vh, std::vector<uint8_t>& vq4,
std::vector<int32_t>& table, std::vector<int32_t>& ids, std::vector<int32_t>& steps, std::vector<float>& q,
int64_t& cap) {
const k::QsaShapes s = k::qsa_real_shapes();
const int64_t HD = s.head_dim, NKV = s.n_head_kv, NH = s.n_head, PS = s.page_size;
const int64_t pages = (ctx + PS - 1) / PS, rows = pages * NKV * PS;
std::mt19937 rng(1234 + fmt);
std::normal_distribution<float> nd(0.f, 1.f);
std::uniform_int_distribution<int> code(-127, 127);
std::uniform_real_distribution<float> sc(0.005f, 0.03f);
if (fmt == 1 || fmt == 2) {
kq.resize(rows * HD); ks.resize(rows * 4);
for (auto& x : kq) x = (int8_t) code(rng);
for (auto& x : ks) x = f2h(sc(rng));
if (fmt == 1) {
vq.resize(rows * HD); vs.resize(rows * 4);
for (auto& x : vq) x = (int8_t) code(rng);
for (auto& x : vs) x = f2h(sc(rng));
} else {
vq4.resize((size_t) (rows * (HD / 32) * 18)); // q4_0 blocks: a finite fp16 scale + random nibbles
for (size_t i = 0; i < vq4.size(); i += 18) {
const uint16_t d = f2h(sc(rng));
vq4[i] = (uint8_t) d; vq4[i + 1] = (uint8_t) (d >> 8);
for (int j = 2; j < 18; ++j) vq4[i + j] = (uint8_t) rng();
}
}
} else {
kh.resize(rows * HD); vh.resize(rows * HD);
for (auto& x : kh) x = f2h(nd(rng) * 1.5f);
for (auto& x : vh) x = f2h(nd(rng));
}
table.resize(pages);
for (int64_t i = 0; i < pages; ++i) table[i] = (int32_t) i;
std::shuffle(table.begin(), table.end(), rng);
cap = k::qsa_selection_width(ctx, s);
ids.assign((size_t) (nq * cap), 0);
steps.assign((size_t) (nq * k::kStepCount), 0);
q.assign((size_t) (nq * NH * HD), 0.f);
for (auto& x : q) x = nd(rng) * 2.0f;
std::vector<int32_t> old_cells;
for (int64_t i = 0; i < nq; ++i) {
const int64_t pos = ctx - nq + i, nkv = pos + 1;
const int64_t w = k::qsa_selection_width(nkv, s);
int32_t* sel = ids.data() + i * cap;
steps[i * k::kStepCount + k::kStepWidth] = (int32_t) w;
if (w == nkv) {
for (int64_t c = 0; c < w; ++c) sel[c] = (int32_t) c;
continue;
}
const int64_t recent = 512, older = w - recent;
if ((int64_t) old_cells.size() != older) {
std::vector<int32_t> all((size_t) (nkv - recent));
for (int64_t c = 0; c < nkv - recent; ++c) all[c] = (int32_t) c;
std::shuffle(all.begin(), all.end(), rng);
old_cells.assign(all.begin(), all.begin() + older);
} else {
std::uniform_int_distribution<int64_t> pick(0, older - 1), any(0, nkv - recent - 1);
for (int r = 0; r < older / 32; ++r) {
const int32_t c = (int32_t) any(rng);
if (std::find(old_cells.begin(), old_cells.end(), c) == old_cells.end()) old_cells[pick(rng)] = c;
}
}
std::vector<int32_t> v(old_cells);
for (int64_t c = nkv - recent; c < nkv; ++c) v.push_back((int32_t) c);
std::sort(v.begin(), v.end());
std::copy(v.begin(), v.end(), sel);
}
}
float time_ms(const std::function<void()>& f, int reps) {
cudaEvent_t e0, e1;
ck(cudaEventCreate(&e0), "event");
ck(cudaEventCreate(&e1), "event");
f();
ck(cudaDeviceSynchronize(), "warm");
ck(cudaEventRecord(e0), "event");
for (int r = 0; r < reps; ++r) f();
ck(cudaEventRecord(e1), "event");
ck(cudaEventSynchronize(e1), "time");
float ms = 0;
ck(cudaEventElapsedTime(&ms, e0, e1), "time");
cudaEventDestroy(e0);
cudaEventDestroy(e1);
return ms / reps;
}
void run(int fmt, int64_t ctx, int64_t nq, int reps) {
const k::QsaShapes s = k::qsa_real_shapes();
const int64_t HD = s.head_dim, NH = s.n_head;
std::vector<int8_t> kq, vq;
std::vector<uint16_t> ks, vs, kh, vh;
std::vector<uint8_t> vq4;
std::vector<int32_t> table, ids, steps;
std::vector<float> q;
int64_t cap = 0;
build(fmt, ctx, nq, kq, vq, ks, vs, kh, vh, vq4, table, ids, steps, q, cap);
k::QsaAttnPools pl;
if (fmt == 1) { pl.k_q = up(kq); pl.v_q = up(vq); pl.k_scale = up(ks); pl.v_scale = up(vs); }
else if (fmt == 2) { pl.k_q = up(kq); pl.k_scale = up(ks); pl.v_q4 = up(vq4); }
else { pl.k_pool = up(kh); pl.v_pool = up(vh); }
pl.page_table = up(table);
const int32_t* d_ids = up(ids);
const int32_t* d_steps = up(steps);
const float* d_q = up(q);
float *d_old = nullptr, *d_new = nullptr, *scratch = nullptr;
const int64_t batch = 32;
ck(cudaMalloc(&d_old, nq * NH * HD * 4), "malloc");
ck(cudaMalloc(&d_new, nq * NH * HD * 4), "malloc");
ck(cudaMalloc(&scratch, batch * k::qsa_decode_attn_scratch_floats(cap, s) * 4), "malloc");
std::printf("# %s KV, ctx %lld, selection %lld cells, %lld queries of %lld heads x %lld dims\n",
fmt == 1 ? "int8" : fmt == 2 ? "int8+q4 V (K8V4)" : "fp16", (long long) ctx, (long long) cap,
(long long) nq, (long long) NH, (long long) HD);
const int64_t counts[] = {16, 64, 256, 1024, 2048, 4096};
for (int64_t nqi : counts) {
if (nqi > nq) continue;
auto old_run = [&]() {
for (int64_t t0 = 0; t0 < nqi; t0 += batch)
k::qsa_decode_attn_batch(d_q + t0 * NH * HD, pl, d_ids + t0 * cap, d_steps + t0 * k::kStepCount, cap,
s, scratch, d_old + t0 * NH * HD, std::min(batch, nqi - t0), nullptr);
};
auto new_run = [&]() {
if (!k::qsa_prompt_attn_batch(d_q, pl, d_ids, d_steps, cap, s, d_new, nqi, nullptr)) {
std::fprintf(stderr, "qsa_prompt_attn_batch refused the pools\n");
std::exit(2);
}
};
old_run(); new_run();
ck(cudaDeviceSynchronize(), "run");
std::vector<float> o((size_t) (nqi * NH * HD)), nw(o.size());
ck(cudaMemcpy(o.data(), d_old, o.size() * 4, cudaMemcpyDeviceToHost), "down");
ck(cudaMemcpy(nw.data(), d_new, nw.size() * 4, cudaMemcpyDeviceToHost), "down");
double diff = 0, scale = 0;
for (size_t i = 0; i < o.size(); ++i) {
diff = std::max(diff, (double) std::fabs(o[i] - nw[i]));
scale = std::max(scale, (double) std::fabs(o[i]));
}
const float ms_old = time_ms(old_run, reps), ms_new = time_ms(new_run, reps);
std::printf("q %5lld: fp32 %8.3f ms volta %8.3f ms %5.2fx max|old-new| %.3g (%.2g of scale)\n",
(long long) nqi, ms_old, ms_new, ms_old / ms_new, diff, scale > 0 ? diff / scale : 0.0);
}
cudaFree((void*) d_ids); cudaFree((void*) d_steps); cudaFree((void*) d_q); cudaFree(d_old); cudaFree(d_new);
cudaFree(scratch);
cudaFree((void*) pl.k_q); cudaFree((void*) pl.v_q); cudaFree((void*) pl.k_scale); cudaFree((void*) pl.v_scale);
cudaFree((void*) pl.v_q4);
cudaFree((void*) pl.k_pool); cudaFree((void*) pl.v_pool); cudaFree((void*) pl.page_table);
}
} // namespace
int main(int argc, char** argv) {
const int64_t ctx = argc > 1 ? std::atoll(argv[1]) : 32768;
const int64_t nq = argc > 2 ? std::atoll(argv[2]) : 2048;
const int reps = argc > 3 ? std::atoi(argv[3]) : 10;
run(1, ctx, nq, reps);
run(2, ctx, nq, reps);
run(0, ctx, nq, reps);
return 0;
}
@@ -0,0 +1,36 @@
# v100/gdn-chunk: chunked GDN prompt recurrence and Volta recurrence variants (2026-10-02)
Measured on the V100-SXM2-16GB x2 (one card, CUDA 12.8, driver 570.x), build:
`-DSTRATA_EXPERIMENTAL_SM60=ON -DCMAKE_CUDA_ARCHITECTURES=70`, Release. `bench/gdn_chunk_bench`
(CUDA events, real GDN geometry S=128 / 16 q/k heads / 48 v heads / C=10240, one `gdn_recurrence`
call per side including the out norm, 5-20 iterations).
## GDN prompt recurrence kernel, one layer, one prompt chunk
| T | pipe (old) | chain-split (default now) | sync-free warp | chunked FMA | chunked wmma |
|-------|-----------:|--------------------------:|---------------:|------------:|-------------:|
| 1024 | 1.056 ms | 1.042 ms (+1%) | 2.712 ms | 6.67 ms | 4.57 ms |
| 4096 | 3.836 ms | 3.600 ms (+6%) | 9.34 ms | 25.0 ms | 17.7 ms |
| 8192 | 7.703 ms | 7.190 ms (+7%) | 18.7 ms | 50.2 ms | 35.4 ms |
- pipe = `gdn_rec_cols_pipe_kernel` (the old path, bit-exact reference).
- chain-split = `gdn_rec_cols_pipe_fast_kernel`: same structure and loads, the k^T W / q^T W
accumulators split 4 ways (FP32-level, NOT bit-exact; `gdn_chunk_parity` bounds it).
- sync-free warp = `gdn_rec_cols_warp_kernel`: warp-shuffle reductions, no __syncthreads,
BIT-EXACT vs pipe (asserted) - but 2.6x SLOWER: its per-thread row loads cost more than the
barriers it removes. Kept as the bitwise control.
- chunked = the FlashQLA-style chunked recurrence (cumsum / kkt / fwd, 64-token chunks). Correct
(parity below) but 4-6x SLOWER than the recurrence as implemented: with 128 threads and the
~84 KB tile staging a CTA only feeds ~4 warps to the tensor cores, and every phase is
latency-bound (measured ablation: staging+Gram+U GEMMs alone = 2.4 ms of the wmma kernel's
4.6 ms at T=1024). Opt-in only (STRATA_GDN_CHUNK=1 wmma / 2 FMA).
## Error bounds (`gdn_chunk_parity`, vs a double-precision transcription of the recurrence)
| path | y max abs | state max abs | note |
|-----------------------------|----------:|--------------:|------|
| pipelined recurrence | 1.1e-06 | 3.0e-08 | the FP32 floor |
| chain-split recurrence | 7.2e-07 | 3.0e-08 | FP32-level, not bit-exact |
| sync-free warp recurrence | 0 | 0 | bit-exact vs the pipelined kernel |
| chunked FMA | 3.1e-06 | 1.2e-07 | FP32-level (reordered sums) |
| chunked wmma | 2.3e-03 | 8.9e-05 | q/k/v and the state staged f32->f16, f32 accumulate |
@@ -0,0 +1,51 @@
# V100 / Swift IQ2_XS / 32k / --kv int8: the KV read path
Test bed: 2x Tesla V100-SXM2-16GB (SM 7.0), CUDA 12.8, one card. No full-engine run; kernel microbench only.
## 1. Audit - where int8 KV is decoded, and whether it is vectorized
The default decode path is the fused split-K attention (`g_fast_attn = true`, `src/core/layer.cpp:42`, chosen at
`layer.cpp:950-952`), which reads the pools directly - no gather:
- K decode: `load8_q8`, `src/kernels/cuda/qsa_decode_attn.cu:46-54`. One lane reads 8 int8 as a `uint2` (8 B) and
one fp16 scale per 64-group, then scalar `(float)c * sc` x8 (I2F + FMUL each). The *load* is vectorized, the
*decode* is scalar.
- V decode: `attn_chunk_kernel`, `qsa_decode_attn.cu:158-179`. Thread `t` owns dimension `t` for all 12 heads:
one int8 load + one fp16 scale + one I2F+FMUL per cell, then 12 FMAs. 1 byte/thread/cell, coalesced to 256 B.
- MTP draft/verify use the same kernel by batch: `src/core/mtp.cpp:503`, `src/core/verify.cpp:647`
(`qsa_decode_attn_batch`).
The non-fast fallback gathers int8 into an fp16 scratch first, then attends over it:
- `kv_gather_q8_kernel`, `src/kernels/cuda/kv_q8.cu:69-99`: `char4` load (4 int8) + 2 fp16 scales, 8 scalar
converts, `ushort4` fp16 store. 4 values/thread.
- `qsa_attend_kernel` then reads the fp16 scratch: `qsa.cu:462-467` (K dot), `qsa.cu:502-505` (V), 2 B/value.
The KV-streaming copy is already wide: `copy_kernel`, `src/kernels/cuda/kv_stream.cu:161-171`, `uint4` (16 B).
## 2. Vectorization
The gather (`kv_gather_q8_kernel`) was 4 values/thread: two `char4` (4 B) loads + two `ushort4` (8 B) stores. The
experimental build (`-DSTRATA_EXPERIMENTAL_SM60=ON`, Pascal/Volta) adds an 8-wide `kv_gather_q8_wide_kernel`: one
`uint2` (8 B) load of codes, one `uint4` (16 B) store of the dequantized fp16, one scale per thread instead of two.
The 8 values lie in one 64-value group, and the arithmetic is unchanged (`(float) code * scale -> f16_from_f32`,
packed two halfs per 32-bit word), so the output is byte-identical. The ready-made engine keeps exactly the
4-wide kernel.
`kv_q8_parity`: OK, worst INT8-vs-FP16 error 0.590 steps (bitwise codes, scales and gather; unchanged).
Microbench (`kv_q8_parity --bench`, 2,051 cells / 2 KV heads / 256 dims, 32k pool, random cells, V100):
| | us/call | GB/s |
|---|---|---|
| before (4-wide) | 15.85 | 401 |
| after (8-wide) | 14.05 | 452 |
+11.4% on the gather. The default decode path (`g_fast_attn`) does not gather; its decode (`load8_q8`,
`qsa_decode_attn.cu:46-54`) already reads 8 int8 with one `uint2` and is arithmetic-bound (8 I2F + 8 FMUL per
cell), which `__byte_perm`/half2 cannot improve while staying bit-exact. The gather is what the non-fast,
streaming and hybrid paths use.
## 3. int8 vs q4_0 vs k8v4 at 32k
TBD
@@ -0,0 +1,70 @@
# V100 (sm_70): the prompt's experts on FP16 tensor cores (2026-10-07)
On sm_70 the prompt path ran the routed experts on llama.cpp's MMQ, whose integer products are `dp4a` there (Volta has
no int8 tensor cores), and IQ1_M layers on the FP16 path (each expert dequantized to global memory, then one cuBLAS
call per product). `gemm_iq_f16_grouped` (`src/kernels/cuda/iq_kernels.cu`) runs a whole MMQ expert group per launch on
the FP16 tensor cores (WMMA, FP32 sums): a block takes 128 weight rows of one expert and up to 256 of its token rows,
dequantizes each weight superblock once into shared memory with `dq_dispatch` (the FP16 path's own formulas), and
streams the FP16 activations through it, the next tile prefetched into registers. sm_70 takes it by default for the
layers MMQ would take and for IQ1_M (which then rides MMQ's grouping); `STRATA_PF_WMMA=0` is the old path,
`STRATA_PF_WMMA=1` turns it on for any CUDA card (not measured elsewhere).
## Rig
As in [2026-10-07-v100-decode-kernels](../2026-10-07-v100-decode-kernels/README.md): V100-SXM2-32GB (PCIe gen3 x16),
2x Xeon Gold 6130 in a container with a ~15-CPU quota, CUDA 12.8; setup's IQ2_XS (gate/up IQ2_S on 34 layers, IQ2_XXS
on 11, IQ1_M on 3; down Q2_0), setup's config (`--prefill auto`: 8,192-token chunks here) plus `--pool-workers 14`.
## Prompt speed
`tools/ab_engine.py`, 3 rounds, the arms' order alternating, one server start per arm and round; the server's own
prompt tokens/s. `orig`: `e8ca9af` as setup built it; `off`: this branch with `STRATA_PF_WMMA=0`; `new`: this branch.
| Prompt | orig | off | new | new vs orig |
| --- | ---: | ---: | ---: | ---: |
| 26,359 tokens (median of 3) | 1,467 tok/s | 1,462 | 1,608 | **+9.6%** |
| 6,345 tokens (median of 3) | 1,390 tok/s | 1,393 | 1,534 | **+10.3%** |
All runs: `ab-runs.jsonl` (the spread between rounds is under 1%). The engine's phase table
(`STRATA_PREFILL_TIMING=1`, the 26,352-token prompt, ms):
| | orig | new |
| --- | ---: | ---: |
| experts gate/up | 3,913 | 3,670 |
| experts down | 2,229 | 1,212 |
| dequant (the IQ1_M layers' FP16 path, and the rest of that phase) | 740 | 575 |
| GPU timeline | 17,391 | 15,847 |
Decode does not use this path (decode tok/s in the same runs: within the noise).
## Accuracy
- `pf_wmma_parity` (synthetic, no model): every format it takes (IQ2_XXS, IQ2_S, IQ1_M gate/up, 1280 x 2560; Q2_0 down,
2560 x 640), 7 experts with 0-300 rows, against a double-precision product of the same FP16 weights and activations:
max error 4.4e-4 to 5.2e-4 of outputs up to ~110 (Q2_0: 2.8e-6 of 1.16) - FP32 summation order.
- **Teacher-forced** (`STRATA_LOGPOS` with `STRATA_LOGPOS_TOPK=20`; a long random-word prompt read by the batched path,
then a continuation read through the decode windows with `--short-read 1024`, each token's log-probability against
the text). MMQ is not a reference either - its activations are q8_1, these are FP16 - so the table puts the change
next to what MMQ alone does when only the chunk size changes:
| Continuation (after) | Compared | argmax agreement | KL (top 20) | perplexity |
| --- | --- | ---: | ---: | --- |
| 363 tokens of prose (26,359-token prompt) | MMQ vs this | 98.3% | 0.0083 | 50.7 / 60.5 |
| | MMQ 8,192 vs 32,768-token chunks | 98.3% | 0.0084 | 50.7 / 50.6 |
| | MMQ 8,192 vs 16,384-token chunks | 93.6% | 0.0177 | 50.7 / 39.2 |
| 327 tokens of Python (12,676-token prompt) | MMQ vs this | 94.5% | 0.0312 | 3.98 / 3.38 |
| | MMQ 8,192 vs 4,096-token chunks | 96.3% | 0.0253 | 3.98 / 3.49 |
| | MMQ 4,096 chunks vs this | 96.3% | 0.0170 | 3.49 / 3.38 |
Two MMQ runs of the same configuration were bit for bit the same. After a long prompt these continuations move this
much from any change of the prompt path's arithmetic (the perplexities swing both ways); the change sits inside
what the chunk size alone does. Two texts are not a quality benchmark; a run against a full-precision reference
(llama.cpp, as in [UNSLOTH_Q4](../../../docs/UNSLOTH_Q4.md)) was not made.
## Notes
- One observation from these runs, not followed up: on the 12,676-token prompt MMQ with `--prefill 4096` read
1,560 tok/s against 1,370 with `auto` (8,192 here) - a single run each.
- Tried and dropped on the way: the FP16 path for chunks of 16K+ tokens (+10% at `--prefill auto:32768`, but superseded
by this, which also wins at setup's chunk size); a row-per-warp hyper-connection down projection (no gain in the
engine). Groups of 32 experts instead of 16: no gain.
@@ -0,0 +1,72 @@
{"round": 0, "arm": "orig", "req": "chat0", "decode": 84.7, "prompt": 106.9, "prompt_n": 34, "n": 32, "text": "```python\ndef merge_sorted_lists(list1: list, list2: list) -> list:\n \"\"\"\n "}
{"round": 0, "arm": "orig", "req": "chat1", "decode": 58.8, "prompt": 93.4, "prompt_n": 27, "n": 32, "text": "A refrigerator operates by utilizing a refrigerant, a fluid with a low boiling p"}
{"round": 0, "arm": "orig", "req": "chat2", "decode": 75.4, "prompt": 103.5, "prompt_n": 29, "n": 32, "text": "1. Set specific, measurable goals to maintain motivation and track your progress"}
{"round": 0, "arm": "orig", "req": "long", "decode": 60.9, "prompt": 1469.9, "prompt_n": 26359, "n": 32, "text": "The list consists entirely of single-word nouns that evoke a variety of natural,"}
{"round": 0, "arm": "off", "req": "chat0", "decode": 90.5, "prompt": 110.7, "prompt_n": 34, "n": 32, "text": "```python\ndef merge_sorted_lists(list1: list, list2: list) -> list:\n \"\"\"\n "}
{"round": 0, "arm": "off", "req": "chat1", "decode": 61.6, "prompt": 95.0, "prompt_n": 27, "n": 32, "text": "A refrigerator operates by utilizing a refrigerant, a fluid with a low boiling p"}
{"round": 0, "arm": "off", "req": "chat2", "decode": 79.7, "prompt": 106.5, "prompt_n": 29, "n": 32, "text": "1. Set specific, measurable goals to maintain motivation and track your progress"}
{"round": 0, "arm": "off", "req": "long", "decode": 63.7, "prompt": 1458.4, "prompt_n": 26359, "n": 32, "text": "The list consists entirely of single-word nouns that evoke a variety of natural,"}
{"round": 0, "arm": "new", "req": "chat0", "decode": 90.7, "prompt": 110.6, "prompt_n": 34, "n": 32, "text": "```python\ndef merge_sorted_lists(list1: list, list2: list) -> list:\n \"\"\"\n "}
{"round": 0, "arm": "new", "req": "chat1", "decode": 61.6, "prompt": 95.2, "prompt_n": 27, "n": 32, "text": "A refrigerator operates by utilizing a refrigerant, a fluid with a low boiling p"}
{"round": 0, "arm": "new", "req": "chat2", "decode": 79.7, "prompt": 107.1, "prompt_n": 29, "n": 32, "text": "1. Set specific, measurable goals to maintain motivation and track your progress"}
{"round": 0, "arm": "new", "req": "long", "decode": 61.6, "prompt": 1608.4, "prompt_n": 26359, "n": 32, "text": "The list consists entirely of single-word nouns that evoke a variety of natural,"}
{"round": 1, "arm": "new", "req": "chat0", "decode": 89.8, "prompt": 110.6, "prompt_n": 34, "n": 32, "text": "```python\ndef merge_sorted_lists(list1: list, list2: list) -> list:\n \"\"\"\n "}
{"round": 1, "arm": "new", "req": "chat1", "decode": 61.2, "prompt": 94.0, "prompt_n": 27, "n": 32, "text": "A refrigerator operates by utilizing a refrigerant, a fluid with a low boiling p"}
{"round": 1, "arm": "new", "req": "chat2", "decode": 79.1, "prompt": 107.1, "prompt_n": 29, "n": 32, "text": "1. Set specific, measurable goals to maintain motivation and track your progress"}
{"round": 1, "arm": "new", "req": "long", "decode": 61.0, "prompt": 1607.2, "prompt_n": 26359, "n": 32, "text": "The list consists entirely of single-word nouns that evoke a variety of natural,"}
{"round": 1, "arm": "off", "req": "chat0", "decode": 90.8, "prompt": 110.9, "prompt_n": 34, "n": 32, "text": "```python\ndef merge_sorted_lists(list1: list, list2: list) -> list:\n \"\"\"\n "}
{"round": 1, "arm": "off", "req": "chat1", "decode": 61.5, "prompt": 95.5, "prompt_n": 27, "n": 32, "text": "A refrigerator operates by utilizing a refrigerant, a fluid with a low boiling p"}
{"round": 1, "arm": "off", "req": "chat2", "decode": 79.8, "prompt": 107.0, "prompt_n": 29, "n": 32, "text": "1. Set specific, measurable goals to maintain motivation and track your progress"}
{"round": 1, "arm": "off", "req": "long", "decode": 63.8, "prompt": 1473.8, "prompt_n": 26359, "n": 32, "text": "The list consists entirely of single-word nouns that evoke a variety of natural,"}
{"round": 1, "arm": "orig", "req": "chat0", "decode": 84.9, "prompt": 106.6, "prompt_n": 34, "n": 32, "text": "```python\ndef merge_sorted_lists(list1: list, list2: list) -> list:\n \"\"\"\n "}
{"round": 1, "arm": "orig", "req": "chat1", "decode": 58.9, "prompt": 92.9, "prompt_n": 27, "n": 32, "text": "A refrigerator operates by utilizing a refrigerant, a fluid with a low boiling p"}
{"round": 1, "arm": "orig", "req": "chat2", "decode": 75.5, "prompt": 103.6, "prompt_n": 29, "n": 32, "text": "1. Set specific, measurable goals to maintain motivation and track your progress"}
{"round": 1, "arm": "orig", "req": "long", "decode": 61.0, "prompt": 1467.3, "prompt_n": 26359, "n": 32, "text": "The list consists entirely of single-word nouns that evoke a variety of natural,"}
{"round": 2, "arm": "orig", "req": "chat0", "decode": 84.0, "prompt": 106.8, "prompt_n": 34, "n": 32, "text": "```python\ndef merge_sorted_lists(list1: list, list2: list) -> list:\n \"\"\"\n "}
{"round": 2, "arm": "orig", "req": "chat1", "decode": 58.8, "prompt": 93.2, "prompt_n": 27, "n": 32, "text": "A refrigerator operates by utilizing a refrigerant, a fluid with a low boiling p"}
{"round": 2, "arm": "orig", "req": "chat2", "decode": 75.5, "prompt": 103.7, "prompt_n": 29, "n": 32, "text": "1. Set specific, measurable goals to maintain motivation and track your progress"}
{"round": 2, "arm": "orig", "req": "long", "decode": 60.7, "prompt": 1458.4, "prompt_n": 26359, "n": 32, "text": "The list consists entirely of single-word nouns that evoke a variety of natural,"}
{"round": 2, "arm": "off", "req": "chat0", "decode": 90.5, "prompt": 110.4, "prompt_n": 34, "n": 32, "text": "```python\ndef merge_sorted_lists(list1: list, list2: list) -> list:\n \"\"\"\n "}
{"round": 2, "arm": "off", "req": "chat1", "decode": 61.5, "prompt": 95.1, "prompt_n": 27, "n": 32, "text": "A refrigerator operates by utilizing a refrigerant, a fluid with a low boiling p"}
{"round": 2, "arm": "off", "req": "chat2", "decode": 79.7, "prompt": 107.2, "prompt_n": 29, "n": 32, "text": "1. Set specific, measurable goals to maintain motivation and track your progress"}
{"round": 2, "arm": "off", "req": "long", "decode": 63.4, "prompt": 1462.2, "prompt_n": 26359, "n": 32, "text": "The list consists entirely of single-word nouns that evoke a variety of natural,"}
{"round": 2, "arm": "new", "req": "chat0", "decode": 90.7, "prompt": 109.7, "prompt_n": 34, "n": 32, "text": "```python\ndef merge_sorted_lists(list1: list, list2: list) -> list:\n \"\"\"\n "}
{"round": 2, "arm": "new", "req": "chat1", "decode": 61.6, "prompt": 95.2, "prompt_n": 27, "n": 32, "text": "A refrigerator operates by utilizing a refrigerant, a fluid with a low boiling p"}
{"round": 2, "arm": "new", "req": "chat2", "decode": 79.8, "prompt": 106.8, "prompt_n": 29, "n": 32, "text": "1. Set specific, measurable goals to maintain motivation and track your progress"}
{"round": 2, "arm": "new", "req": "long", "decode": 61.9, "prompt": 1608.2, "prompt_n": 26359, "n": 32, "text": "The list consists entirely of single-word nouns that evoke a variety of natural,"}
{"round": 0, "arm": "orig", "req": "chat0", "decode": 85.0, "prompt": 106.9, "prompt_n": 34, "n": 32, "text": "```python\ndef merge_sorted_lists(list1: list, list2: list) -> list:\n \"\"\"\n "}
{"round": 0, "arm": "orig", "req": "chat1", "decode": 58.5, "prompt": 93.2, "prompt_n": 27, "n": 32, "text": "A refrigerator operates by utilizing a refrigerant, a fluid with a low boiling p"}
{"round": 0, "arm": "orig", "req": "chat2", "decode": 75.6, "prompt": 103.9, "prompt_n": 29, "n": 32, "text": "1. Set specific, measurable goals to maintain motivation and track your progress"}
{"round": 0, "arm": "orig", "req": "long", "decode": 69.1, "prompt": 1390.1, "prompt_n": 6345, "n": 32, "text": "The list consists entirely of single, lowercase English words that appear to be "}
{"round": 0, "arm": "off", "req": "chat0", "decode": 89.8, "prompt": 110.8, "prompt_n": 34, "n": 32, "text": "```python\ndef merge_sorted_lists(list1: list, list2: list) -> list:\n \"\"\"\n "}
{"round": 0, "arm": "off", "req": "chat1", "decode": 61.6, "prompt": 94.2, "prompt_n": 27, "n": 32, "text": "A refrigerator operates by utilizing a refrigerant, a fluid with a low boiling p"}
{"round": 0, "arm": "off", "req": "chat2", "decode": 79.8, "prompt": 105.2, "prompt_n": 29, "n": 32, "text": "1. Set specific, measurable goals to maintain motivation and track your progress"}
{"round": 0, "arm": "off", "req": "long", "decode": 72.9, "prompt": 1392.7, "prompt_n": 6345, "n": 32, "text": "The list consists entirely of single, lowercase English words that appear to be "}
{"round": 0, "arm": "new", "req": "chat0", "decode": 70.1, "prompt": 102.0, "prompt_n": 34, "n": 32, "text": "```python\ndef merge_sorted_lists(list1: list, list2: list) -> list:\n \"\"\"\n "}
{"round": 0, "arm": "new", "req": "chat1", "decode": 48.3, "prompt": 80.6, "prompt_n": 27, "n": 32, "text": "A refrigerator operates by utilizing a refrigerant, a fluid with a low boiling p"}
{"round": 0, "arm": "new", "req": "chat2", "decode": 56.1, "prompt": 90.1, "prompt_n": 29, "n": 32, "text": "1. Set specific, measurable goals to maintain motivation and track your progress"}
{"round": 0, "arm": "new", "req": "long", "decode": 57.9, "prompt": 1533.9, "prompt_n": 6345, "n": 32, "text": "The list consists entirely of single, lowercase English nouns that appear to be "}
{"round": 1, "arm": "new", "req": "chat0", "decode": 90.5, "prompt": 110.6, "prompt_n": 34, "n": 32, "text": "```python\ndef merge_sorted_lists(list1: list, list2: list) -> list:\n \"\"\"\n "}
{"round": 1, "arm": "new", "req": "chat1", "decode": 61.1, "prompt": 95.4, "prompt_n": 27, "n": 32, "text": "A refrigerator operates by utilizing a refrigerant, a fluid with a low boiling p"}
{"round": 1, "arm": "new", "req": "chat2", "decode": 79.6, "prompt": 106.9, "prompt_n": 29, "n": 32, "text": "1. Set specific, measurable goals to maintain motivation and track your progress"}
{"round": 1, "arm": "new", "req": "long", "decode": 74.9, "prompt": 1534.9, "prompt_n": 6345, "n": 32, "text": "The list consists entirely of single, lowercase English nouns that appear to be "}
{"round": 1, "arm": "off", "req": "chat0", "decode": 54.9, "prompt": 92.0, "prompt_n": 34, "n": 32, "text": "```python\ndef merge_sorted_lists(list1: list, list2: list) -> list:\n \"\"\"\n "}
{"round": 1, "arm": "off", "req": "chat1", "decode": 41.8, "prompt": 69.1, "prompt_n": 27, "n": 32, "text": "A refrigerator operates by utilizing a refrigerant, a fluid with a low boiling p"}
{"round": 1, "arm": "off", "req": "chat2", "decode": 48.9, "prompt": 79.0, "prompt_n": 29, "n": 32, "text": "1. Set specific, measurable goals to maintain motivation and track your progress"}
{"round": 1, "arm": "off", "req": "long", "decode": 49.3, "prompt": 1387.5, "prompt_n": 6345, "n": 32, "text": "The list consists entirely of single, lowercase English words that appear to be "}
{"round": 1, "arm": "orig", "req": "chat0", "decode": 65.2, "prompt": 99.3, "prompt_n": 34, "n": 32, "text": "```python\ndef merge_sorted_lists(list1: list, list2: list) -> list:\n \"\"\"\n "}
{"round": 1, "arm": "orig", "req": "chat1", "decode": 45.7, "prompt": 76.8, "prompt_n": 27, "n": 32, "text": "A refrigerator operates by utilizing a refrigerant, a fluid with a low boiling p"}
{"round": 1, "arm": "orig", "req": "chat2", "decode": 53.8, "prompt": 86.3, "prompt_n": 29, "n": 32, "text": "1. Set specific, measurable goals to maintain motivation and track your progress"}
{"round": 1, "arm": "orig", "req": "long", "decode": 51.6, "prompt": 1380.8, "prompt_n": 6345, "n": 32, "text": "The list consists entirely of single, lowercase English words that appear to be "}
{"round": 2, "arm": "orig", "req": "chat0", "decode": 65.4, "prompt": 99.2, "prompt_n": 34, "n": 32, "text": "```python\ndef merge_sorted_lists(list1: list, list2: list) -> list:\n \"\"\"\n "}
{"round": 2, "arm": "orig", "req": "chat1", "decode": 46.8, "prompt": 78.5, "prompt_n": 27, "n": 32, "text": "A refrigerator operates by utilizing a refrigerant, a fluid with a low boiling p"}
{"round": 2, "arm": "orig", "req": "chat2", "decode": 54.6, "prompt": 87.3, "prompt_n": 29, "n": 32, "text": "1. Set specific, measurable goals to maintain motivation and track your progress"}
{"round": 2, "arm": "orig", "req": "long", "decode": 51.0, "prompt": 1392.7, "prompt_n": 6345, "n": 32, "text": "The list consists entirely of single, lowercase English words that appear to be "}
{"round": 2, "arm": "off", "req": "chat0", "decode": 77.5, "prompt": 107.6, "prompt_n": 34, "n": 32, "text": "```python\ndef merge_sorted_lists(list1: list, list2: list) -> list:\n \"\"\"\n "}
{"round": 2, "arm": "off", "req": "chat1", "decode": 51.7, "prompt": 86.6, "prompt_n": 27, "n": 32, "text": "A refrigerator operates by utilizing a refrigerant, a fluid with a low boiling p"}
{"round": 2, "arm": "off", "req": "chat2", "decode": 61.0, "prompt": 94.8, "prompt_n": 29, "n": 32, "text": "1. Set specific, measurable goals to maintain motivation and track your progress"}
{"round": 2, "arm": "off", "req": "long", "decode": 55.5, "prompt": 1397.5, "prompt_n": 6345, "n": 32, "text": "The list consists entirely of single, lowercase English words that appear to be "}
{"round": 2, "arm": "new", "req": "chat0", "decode": 78.1, "prompt": 107.7, "prompt_n": 34, "n": 32, "text": "```python\ndef merge_sorted_lists(list1: list, list2: list) -> list:\n \"\"\"\n "}
{"round": 2, "arm": "new", "req": "chat1", "decode": 52.4, "prompt": 87.4, "prompt_n": 27, "n": 32, "text": "A refrigerator operates by utilizing a refrigerant, a fluid with a low boiling p"}
{"round": 2, "arm": "new", "req": "chat2", "decode": 61.9, "prompt": 96.5, "prompt_n": 29, "n": 32, "text": "1. Set specific, measurable goals to maintain motivation and track your progress"}
{"round": 2, "arm": "new", "req": "long", "decode": 59.7, "prompt": 1532.3, "prompt_n": 6345, "n": 32, "text": "The list consists entirely of single, lowercase English nouns that appear to be "}
+15 -1
View File
@@ -27,7 +27,7 @@ select "old" kernels everywhere: which kernel runs is decided per architecture w
| Part of the prompt path | On sm_70 |
| --- | --- |
| MoE experts (ggml MMQ) | `dp4a` kernels (Volta has no int8 tensor cores) |
| MoE experts | opt-in (`STRATA_PF_WMMA=1`, only when every visible card is compute capability 7+; MMQ otherwise): `gemm_iq_f16_grouped`: a group of experts per launch on the FP16 tensor cores, the weights dequantized in shared memory (+10% prompt speed against MMQ's `dp4a` kernels, [bench](../bench/results/2026-10-07-v100-prompt-experts/README.md); FP16 activations instead of MMQ's q8_1, so the answers differ) |
| Dense projections (dequantized weights) | FP16 tensor-core GEMMs (cuBLAS / CUTLASS `s884`) |
| BF16 projections (hyper-connection, router, indexer, ...) | converted to FP16 and run on the FP16 tensor cores (#655, #540; `STRATA_BF16_TC=0`: cuBLAS BF16, an FP32 SIMT kernel on Volta) |
| QSA attention for decode and verify windows (and prompts with `STRATA_PROMPT_ATTN_OLD=1`) | #540's kernel (fewer shuffles, bit-exact; `STRATA_ATTN_PRE75=0`: the one other cards run) |
@@ -89,3 +89,17 @@ kernels' output, GPU work per verify window 22.8 -> 21.2 ms on a V100-SXM2 in th
sm_70 only when `STRATA_SM70_TABLE=1` is set. They become the default once the contributor has confirmed them on a V100 with
the 0.1.41 code. Without the variable sm_70 runs what 0.1.40.3 ran. The single switches (`STRATA_EXP_MODE`, `STRATA_MMVQ_IL`,
`STRATA_GR_FAST`) still apply on top.
## More opt-in switches (CUDA 12 experimental build)
None of these is on by default. Each was measured by its contributor on a V100, not by the maintainers.
| Switch | What it does | Contributor's number |
| --- | --- | --- |
| `STRATA_FUSE_DECODE=1` | the decode GEMV / MoE operator fusions of #1097 (gate/up + SwiGLU in one kernel, SwiGLU + quantizer in one kernel, all activation images of a vector in one pass, two BF16 projections in one kernel); bitwise the unfused kernels | 4-16 us per token saved, not visible end to end |
| `STRATA_PF_WMMA=1` | the FP16 tensor-core prompt experts (above); also takes IQ4_NL down projections (K=640, #1771) | +10% prompt speed (#1401) |
| `STRATA_PF_WMMA2=1` | a second prompt-expert kernel for IQ2_S gate/up and IQ4_NL down (#2356) | +2.5-4.3% prompt speed |
| `STRATA_ARGMAX_ROWS_SM70=1` | the multi-block greedy pick on sm_7x (#2357), bitwise the one-block pick | +0.7-0.8% decode |
| `STRATA_GR_NORM_FAST=1` | the register-split hyper-connection norm on CUDA (#2358) | +0.5-0.6% decode |
| `STRATA_Q8_GATHER_WIDE=0` | turns off the 8-wide int8 KV gather (#1095) that the experimental build uses below compute capability 7.5 | +11% on the gather kernel |
| `STRATA_GDN_REC_WARP=2` | the chain-split DeltaNet recurrence of the prompt on a V100 (#1098); changes the summation order (FP32 level), so the default stays the pipelined kernel; `1` is the bit-exact sync-free variant, `STRATA_GDN_CHUNK=1` the chunked path | +6-9% on the recurrence |
+56 -2
View File
@@ -11,7 +11,7 @@ and their output stay exactly as they were. Numbers are the reporters' own, on o
| Cards | Compute capability | How it runs | What is different on it | Reported |
| --- | --- | --- | --- | --- |
| Tesla P100 | 6.0 | the CUDA 12 engine | `__dp4a` emulated (bit-exact); BF16 projections through fp32 | 2x P100, IQ3_S, engine 0.1.39: prompt 526-532 tok/s, decode 28-32 tok/s at 128K prompt tokens, 3 of 3 needle checks at 122K ([report](../bench/results/2026-10-06-community-2x-p100/README.md), #1157) |
| Tesla P100 | 6.0 | the CUDA 12 engine | `__dp4a` emulated (bit-exact); BF16 projections through fp32; opt-in: `STRATA_Q8_SM60=1` runs the Q8_0 dense projections and head on a GP100 kernel ([below](#pascal-gp100-a-q8_0-decode-kernel-opt-in)) | 2x P100, IQ3_S, engine 0.1.39: prompt 526-532 tok/s, decode 28-32 tok/s at 128K prompt tokens, 3 of 3 needle checks at 122K ([report](../bench/results/2026-10-06-community-2x-p100/README.md), #1157); PH402 (4 GP100 dies), IQ3_XXS: decode 28.3 -> 38.9 tok/s with `STRATA_Q8_SM60=1` and a Q8_0 dense shard |
| Tesla P40 / P4, GTX 10 series | 6.1 | the CUDA 12 engine | BF16 projections through fp32 (cuBLAS has no BF16 GEMM there, #395); the dense weights dequantized by a wide kernel, expert mode 8 and its own interleaved-matvec table; opt-in `STRATA_DENSE_F32=1`: the large dense GEMMs as `cublasSgemm` ([below](#tesla-p40-sm_61-what-was-measured-and-changed)) | P40, IQ3_S, engine 0.1.30: prompt 217-374 tok/s, decode 30-33 tok/s (#395); 0.1.43.1 with the sm_61 changes: prompt 255 tok/s at 565 tokens (was 205), decode 37-38 tok/s (was 34-35); with `STRATA_DENSE_F32=1` 464-474 tok/s at 7K tokens (was 360-432) |
| Tesla V100, Titan V | 7.0 | the CUDA 12 engine | BF16 projections on the FP16 tensor cores (#655, #540); the prompt attention on `mma.m8n8k4` (#600); a leaner attention kernel (#540) | V100-PCIE-32GB, UD-IQ4_XS: prompt 1,123-1,251 tok/s (#600); V100 32GB, IQ2_XS: prompt +22% from #540 |
| RTX 20 (Turing) | 7.5 | **supported**, the ready-made engine | opt-in: `STRATA_BF16_TC=1` runs the BF16 projections on the FP16 tensor cores | RTX 2080 Ti, Q2_0: prompt +15-18% (#655) |
@@ -95,8 +95,62 @@ sums round differently): #540 measured a mean KL of 8.4e-3 on the next-token dis
(the same top-1 in 23), the size of other summation-order changes; #655 a worst relative difference of 3.5e-5 per
product on an RTX 2080 Ti.
### Pascal GP100: a Q8_0 decode kernel (opt-in)
GP100 (P100, PH402) is the one Pascal chip without `__dp4a`, and the decode kernels are written for the cards that have
it: on a GP100 die the dense projections of a verify window read their weights at 40-80 GB/s of its ~730, decoding K-
and i-quant blocks (Q6_K, IQ4_XS, Q4_K, IQ3_S, ...) one int at a time. Two changes, both measured on a PH402 only:
- **`STRATA_Q8_SM60=1`** packs every Q8_0 dense matrix and the head into the planes of `STRATA_Q8_PACKED` (any shape)
and runs them on `src/kernels/cuda/q8_sm60.cuh`: a warp (half or quarter warp for narrow rows) per row, 16-byte
weight loads, the window's q8_1 activations copied once per workgroup into shared memory as an int8 plane, the dot
on `STRATA_DP4A` (vmad), a shuffle sum - no barrier per row. Shapes it declines (a 6144-wide row with 7-8 columns)
keep the usual kernel. Not bitwise the exact kernels (the per-32 products are added in another order). The packed
copies cost their size in VRAM beside the GGUF layout the prompt path reads (Flash-Next: 2.9 GiB of dense
projections over the stages and 0.6 GiB for the head).
- The GSQ-RCO packs have no Q8_0 dense matrices, so the kernel needs a copy of the model whose dense projections and head are
Q8_0: `python tools/q8_dense_gguf.py <model>-00001-of-00002.gguf <new folder>` writes one: every shard that holds
such matrices is converted (Swift 1.5 keeps them in both of its shards) and the rest are hard-linked beside them
(+3.5 GiB; the experts keep their offsets, so the native pack is reused). Point `--native` and
`--ple-gguf` at the new folder. Requantizing costs at most 0.4% of a tensor's |w|max (Q8_0 is finer than the
sources).
- **Opt-in `STRATA_IQ_STAGE_TABLES=1`**: IQ3_XXS's and IQ3_S's codebooks and sign-mask tables are staged in shared memory by
the grouped expert kernels (IQ3_XXS's ported from shinbunbun/llama-cpp-p100-patches 29 and 30, IQ3_S's the same for its
sign bytes; bitwise the same output). IQ3_S was the one gate/up format whose codebook those kernels still read from
global memory: the contributor measured a verify window's layer of IQ3_S experts (20 experts, 24 entries) 24% faster on a
GP100 die (517 -> 393 us with a Q2_0 down projection, 492 -> 369 us with IQ4_NL), and Swift 1.5 IQ3_XXS (13 of its 48
layers are IQ3_S) 3.2% faster at 1M context (39.3 -> 40.5 tok/s); IQ3_XXS's tables alone were within noise (+0-4%). The
maintainers' interleaved A/Bs on a Tesla P100 (PCIe, IQ3_XXS pack and IQ3_S pack, 5-6 pairs each) showed no end-to-end
change (decode 0.97-1.03x, inside the noise of that box), so it is off by default (the contributor's version had it on
for compute capability 6.0). On an RTX 3090 Ti, forced on, the same IQ3_S layers took 3-13% longer (those kernels already
read at 490-665 GB/s there).
- Neither change is measured on compute capability 6.1 (P40, P4, GTX 10 series), which has `__dp4a`. Both build for
sm_61, and on a card with `__dp4a` the Q8_0 kernel's dot is the hardware instruction (`tools/q8_sm60_check.cu`
passes on an RTX 3090 Ti); numbers from a 6.1 card with `STRATA_Q8_SM60=1` or `STRATA_IQ_STAGE_TABLES=1` would
show whether either helps there.
Measured on a PH402 SKU 200 (two boards, four GP100 dies of 48 SMs and 32 GB HBM2), application clocks locked at
1050 MHz, Windows 11, driver 581.80 (TCC), CUDA 12.9, engine 0.1.40.2; Flash-Next IQ3_XXS, 32K, `--layer-split 12,24,36
--prefill 2048`; greedy, 256 tokens, medians of 2-3 interleaved starts, decode tok/s:
| | ~10.7K-token document | the same, cached | short reasoning | code | mean |
| --- | ---: | ---: | ---: | ---: | ---: |
| GSQ-RCO shard, exact kernels | 28.8 | 29.4 | 28.4 | 26.8 | 28.3 |
| Q8_0 dense shard, `STRATA_Q8_PACKED=1` | 27.5 | 31.0 | 34.4 | 31.8 | 31.1 |
| Q8_0 dense shard, `STRATA_Q8_SM60=1` | 37.5 | 38.4 | 41.2 | 38.5 | 38.9 |
GPU time per verify window (`STRATA_VERIFY_PROFILE`): dense projections 19.2 -> 11.2 ms, head 4.25 -> 2.1 ms; the
draft policy then picks longer windows (2.10 -> 2.31 tokens per window). Prompt reads are unchanged (437-438 tok/s at
10.7K). `tools/q8_sm60_check.cu` checks the kernel against a CPU reference on these shapes (1-8 columns) and times it.
Two things that mattered as much on this card: its default application clock is 759 MHz, and a layer split leaves
each die idle most of a window, so the dies decode below 1050 MHz unless the clocks are locked
(`nvidia-smi -i <dies> -ac 715,1050` as administrator; 25.0 -> 29.1 tok/s at 10.7K context). And a second engine on
the same PC that pins its threads to the same logical CPUs halves this one's decode while it runs (the host thread
is time-sliced); keeping the two on different logical CPUs (SMT siblings) avoided it.
A/B switches: `STRATA_DEQUANT_WIDE=0`, `STRATA_SM61_TABLE=0` (sm_61: the kernels 0.1.43.1 ran), `STRATA_DENSE_F32=1` (Pascal, opt-in),
`STRATA_BF16_TC=0|1`, `STRATA_PROMPT_ATTN_OLD=1` (the decode kernel for prompts), `STRATA_ATTN_PRE75=0`
`STRATA_Q8_SM60=0|1` (Pascal GP100, opt-in), `STRATA_BF16_TC=0|1`, `STRATA_PROMPT_ATTN_OLD=1` (the decode kernel for prompts), `STRATA_ATTN_PRE75=0`
(#540's kernel off; on gfx103x with HIP that kernel is the default, see the AMD table above, and `=1` turns it on for
another wave32 AMD card). [NVIDIA_V100.md](NVIDIA_V100.md) has the V100 build, its measurements and the parity test.
+8
View File
@@ -26,6 +26,14 @@ namespace strata::kernels {
/// `strata::core::WeightRef::ne0/ne1` already report.
void bf16_gemv(const uint16_t* x, const uint16_t* w, float* y, int64_t n_in, int64_t n_out, void* stream);
/// TWO weight matrices from ONE kernel (llama.cpp's `*_mul_mat_multi` shape): `y1 = w1 @ x`, `y2 = w2 @ x`.
/// One warp computes row o of both matrices with two accumulators over one lane-strided pass, so each output
/// is bitwise what `bf16_gemv` produced for that matrix wherever `bf16_gemv` used its warp kernel
/// (`n_out >= 64`); a matrix below that threshold falls back to the plain call to keep the naive kernel's
/// summation order. `n_out1` or `n_out2` may be 0 for a one-sided call.
void bf16_gemv_pair(const uint16_t* x, const uint16_t* w1, float* y1, int64_t n_out1, const uint16_t* w2,
float* y2, int64_t n_out2, int64_t n_in, void* stream);
/// The row-split variant, for the same reason `s_gemv_split` exists: with one thread per output row the
/// parallelism IS the output width, and `ssm_alpha` has 48 of them over 48 SMs. One warp per row, lanes
/// striding the reduction axis - which is also what makes the access pattern coalesced in this layout.
+16
View File
@@ -0,0 +1,16 @@
#pragma once
// STRATA_FUSE_DECODE=1: the operator fusions of PR #1097 (gate/up GEMV + SwiGLU in one kernel, SwiGLU + intermediate
// quantizer in one kernel, every activation image of x in one pass, two BF16 projections in one kernel). They are
// compiled only into the experimental build (STRATA_EXPERIMENTAL_SM60, the CUDA 12 engine for Pascal / Volta) and are
// bitwise what the unfused sequences produce. Opt-in: unset or 0 keeps the unfused kernels.
#include <cstdlib>
namespace strata::kernels {
inline bool fuse_decode() {
static const bool on = [] {
const char* e = std::getenv("STRATA_FUSE_DECODE");
return e != nullptr && e[0] == '1';
}();
return on;
}
} // namespace strata::kernels
+5
View File
@@ -121,6 +121,11 @@ bool native_expert_expdec_takes(const NativeExpertLayout& L, bool& gu, bool& dow
/// `iq_mmvq` and `native_expert_grouped` decode each weight part once and apply it to every column / entry;
/// true selects the older kernels that decode it again per column (STRATA_OLD_IQ_MMVQ=1 at startup). Both give
/// bitwise the same results. Set before graph capture; captured graphs keep the kernels they captured.
/// Volta prompt experts (STRATA_PF_WMMA): Y[rows of expert e] = X[rows] . W_e^T for a group of experts, W_e at
/// W + e * expert_bytes (n_out rows of K values of type ty, GGUF blocks), X FP16 (ldx), rows bounds[e]..bounds[e+1],
/// Y FP32 (ldy). FP16 tensor cores, FP32 sums. false: not launched (shape or type not covered). CUDA only.
bool gemm_iq_f16_grouped(int ty, const void* W, size_t expert_bytes, int n_out, int K, const void* X, int ldx,
const int32_t* bounds, int n_experts, int max_rows, float* Y, int ldy, void* stream);
void iq_set_old_kernels(bool old);
bool iq_old_kernels();
+5
View File
@@ -108,6 +108,11 @@ bool native_q8_0_packed_eligible(int n_in, int n_out);
void native_q8_0_pack_host(const void* gguf_blocks, void* out, int n_in, int n_out);
void native_q8_0_packed_register(const void* gguf_weights, const void* packed, int n_in, int n_out);
void native_q8_0_packed_unregister(const void* gguf_weights);
/// STRATA_Q8_SM60=1 (opt-in, Pascal GP100): every Q8_0 dense matrix is packed as above whatever its shape, and the
/// Q8_0 decode GEMVs run a kernel written for compute capability 6.0 (q8_sm60.cuh; not bitwise the exact kernels).
/// native_q8_0_sm60_pack packs a device matrix here (the head) and owns the copy until native_q8_0_sm60_release.
bool native_q8_0_sm60_pack(const void* weights, int n_in, int n_out, const char* what);
void native_q8_0_sm60_release(const void* weights);
/// STRATA_Q6_PACKED=1 (opt-in): a packed copy of a Q6_K matrix (the output heads) - the same bytes as ql / qh /
/// scales / d planes - that native_q6_k_mmvq calls on `weights` read instead (bitwise equal outputs). The copy is
+32
View File
@@ -29,6 +29,38 @@ void quantize_q8_0(const float* x, uint8_t* blocks, int64_t n, void* stream);
// null. `quantize_q8_0` is unchanged and still matches ggml's bytes, which is what `moe_hit_parity` checks.
void quantize_q8_0_scaled(const float* x, uint8_t* blocks, float* scales, int64_t n, void* stream);
// ===================== fused silu(gate) * up + quantize =====================
//
// One kernel where two ran: the standalone SwiGLU pass wrote the products and the quantizer read them back.
// The products are computed in registers, stored to `gate_out` exactly as the standalone kernels stored them,
// and quantized from those same values - the bytes out are what the two-kernel pipeline produced, with one
// launch and one round trip over the intermediate gone. `gate_out` may alias `gate`.
//
// `swilu_kind` selects the SwiGLU expression this replaces: 0 = the double-precision `ref/moe.py` form
// (`shared_expert`'s legacy kernel), 1 = the S2 expert path's float `__expf` form, 2 = the pinned CUDA
// native form. The expressions live in `strata/kernels/swiglu.cuh`, one copy each.
// n pairs -> ggml block_q8_0 for the products.
void swilu_quantize_q8_0(const float* gate, const float* up, float* gate_out, int64_t n, int swilu_kind,
uint8_t* blocks, void* stream);
// The same blocks plus the CPU contract's fp32 scales (`quantize_q8_0_scaled`).
void swilu_quantize_q8_0_scaled(const float* gate, const float* up, float* gate_out, int64_t n, int swilu_kind,
uint8_t* blocks, float* scales, void* stream);
// The same for the Q8_K contract (n a multiple of 256).
void swilu_quantize_q8_K(const float* gate, const float* up, float* gate_out, int64_t n, int swilu_kind,
uint8_t* blocks, void* stream);
// ===================== every activation image of x in ONE pass =====================
//
// The layer start wants 2-3 images of the SAME x (ggml block_q8_0, block_q8_K, bf16) and the engine ran one
// kernel per image - three reads and three launches. This produces whichever images the caller asks for in
// one pass; a null pointer skips that image. The bytes of each image are what its standalone kernel wrote
// (the per-block math is shared with those kernels). n must be a multiple of 256 (the Q8_K block).
void quantize_act_images(const float* x, int64_t n, uint8_t* q8_0_blocks, uint8_t* q8_K_blocks,
uint16_t* bf16, void* stream);
// The inverse, for round-trip checks: each element becomes `q * d16`.
void dequant_q8_0(const uint8_t* blocks, float* x, int64_t n, void* stream);
+113
View File
@@ -0,0 +1,113 @@
// include/strata/kernels/quantize_act_dev.cuh - the per-block activation quantizers, ONE copy each.
//
// The fusion work (V100) folds `silu(gate) * up` and the activation quantizer that follows it into one
// kernel. For that to be bit-exact the fused kernel must quantize EXACTLY what `quantize_act.cu`'s
// kernels quantize - same amax order, same double `rint`, same clamps. A second copy of the math is a
// second thing to drift, so `quantize_act.cu` and the fused kernels both include this file and call the
// same functions. The standalone kernels are thin wrappers around these; there is no other difference.
#pragma once
#include "strata/kernels/f16_bits.hpp"
#include <cuda_runtime.h>
#include <cmath>
#include <cstdint>
#include <cstring>
namespace strata::kernels {
constexpr int Q8_0_BLOCK = 32;
constexpr int Q8_0_BLOCK_BYTES = 34;
constexpr int Q8_K_BLOCK = 256;
constexpr int Q8_K_BLOCK_BYTES = 292;
/// ggml's `nearest_int` (ggml-quants.c L621). The magic constant is 1.5 * 2^23; it is transcribed rather
/// than rewritten as `rintf` because the two differ on exact ties - which is the whole point of it.
__device__ __forceinline__ int nearest_int_dev(float fval) {
const float val = fval + 12582912.0f;
int i;
memcpy(&i, &val, 4);
return (i & 0x007fffff) - 0x00400000;
}
/// `block_q8_0` for one 32-element block, ggml's bytes: `d32 = amax/127` in fp32, `d` stored fp16, the
/// QUANTIZED INTEGERS divided by `d32` (not by the stored fp16), and `rint` in DOUBLE. See the three
/// subtleties in `quantize_act.cu`'s header comment - every one of them is load-bearing.
__device__ __forceinline__ void quantize_q8_0_block(const float* __restrict__ xb, uint8_t* __restrict__ out) {
float amax = 0.0f;
for (int i = 0; i < Q8_0_BLOCK; ++i) amax = fmaxf(amax, fabsf(xb[i]));
if (amax == 0.0f) {
const uint16_t zb = f16_from_f32(0.0f);
out[0] = (uint8_t) (zb & 0xFF);
out[1] = (uint8_t) (zb >> 8);
for (int i = 0; i < Q8_0_BLOCK; ++i) out[2 + i] = 0;
return;
}
const float d32 = amax / 127.0f;
const uint16_t d16bits = f16_from_f32(d32);
out[0] = (uint8_t) (d16bits & 0xFF);
out[1] = (uint8_t) (d16bits >> 8);
for (int i = 0; i < Q8_0_BLOCK; ++i) {
double q = rint((double) xb[i] / (double) d32);
if (q > 127.0) q = 127.0;
if (q < -128.0) q = -128.0;
out[2 + i] = (uint8_t) (int8_t) q;
}
}
/// `block_q8_0` bytes PLUS the fp32 scale and the CPU's rounding rule (round half away from zero) - the
/// `quantize_q8_0_scaled_kernel` body, verbatim, so a hit and a CPU miss agree.
__device__ __forceinline__ void quantize_q8_0_scaled_block(const float* __restrict__ xb,
uint8_t* __restrict__ out, float* __restrict__ scale_out) {
float amax = 0.0f;
for (int i = 0; i < Q8_0_BLOCK; ++i) amax = fmaxf(amax, fabsf(xb[i]));
const float s = amax > 0.f ? amax / 127.f : 0.f;
const float inv = s > 0.f ? 1.f / s : 0.f;
*scale_out = s;
const uint16_t d16bits = f16_from_f32(s);
out[0] = (uint8_t) (d16bits & 0xFF);
out[1] = (uint8_t) (d16bits >> 8);
for (int i = 0; i < Q8_0_BLOCK; ++i) {
const float t = xb[i] * inv;
const float r = t + (t >= 0.f ? 0.5f : -0.5f);
int v = (int) r;
v = v < -127 ? -127 : (v > 127 ? 127 : v);
out[2 + i] = (uint8_t) (int8_t) v;
}
}
/// `block_q8_K` for one 256-element block - the `quantize_q8_K_kernel` body, verbatim (including the
/// zero-block divergence note: bsums are zeroed where ggml leaves them unwritten).
__device__ __forceinline__ void quantize_q8_K_block(const float* __restrict__ xb, uint8_t* __restrict__ out) {
float* d = (float*) out;
int8_t* qs = (int8_t*) (out + 4);
int16_t* bsums = (int16_t*) (out + 4 + Q8_K_BLOCK);
float max = 0.0f, amax = 0.0f;
for (int j = 0; j < Q8_K_BLOCK; ++j) {
const float ax = fabsf(xb[j]);
if (ax > amax) {
amax = ax;
max = xb[j];
}
}
if (amax == 0.0f) {
*d = 0.0f;
for (int j = 0; j < Q8_K_BLOCK; ++j) qs[j] = 0;
for (int j = 0; j < Q8_K_BLOCK / 16; ++j) bsums[j] = 0;
return;
}
const float iscale = -127.0f / max;
for (int j = 0; j < Q8_K_BLOCK; ++j) {
const int v = nearest_int_dev(__fmul_rn(iscale, xb[j]));
qs[j] = (int8_t) min(127, v);
}
for (int j = 0; j < Q8_K_BLOCK / 16; ++j) {
int sum = 0;
for (int ii = 0; ii < 16; ++ii) sum += qs[j * 16 + ii];
bsums[j] = (int16_t) sum;
}
*d = 1.0f / iscale;
}
} // namespace strata::kernels
+17
View File
@@ -130,4 +130,21 @@ void s_gemv_q8k_split(const uint8_t* x_q8k, const uint8_t* codes, const float* s
void s_gemv_q8_0_split(const uint8_t* x_q8_0, const uint8_t* codes, const float* scales, const float* offset,
float* y, int64_t n_in, int64_t n_out, const SForm& form, void* stream);
/// GATE/UP DUAL GEMV + SwiGLU IN ONE KERNEL (llama.cpp's `mul_mat_gated`): `out[o] = silu(gate_row_o) *
/// up_row_o`, one read of the activation for both projections, the `up` intermediate never materialised.
///
/// Each row is accumulated by the same row function its standalone kernel uses
/// (`strata/kernels/s_rowdev.cuh`) and the SwiGLU is the shared expression (`strata/kernels/swiglu.cuh`),
/// so the output is BITWISE what `gemv(gate)` + `gemv(up)` + the standalone SwiGLU produced - checked by
/// `fusions_parity`. Both forms may be any S-family form (the two sides are dispatched independently;
/// a Q8_0 side and a Q8_K side in one kernel is fine).
///
/// `swilu_kind`: 0 = the double-precision `ref/moe.py` form, 1 = the float `__expf` form, 2 = the pinned
/// CUDA native form. Returns false when a side's form is outside the warp-per-row kernel's contract
/// (the caller keeps its unfused sequence).
bool s_gemv_pair_silu(const uint8_t* x_q8_0, const uint8_t* x_q8k, const SForm& form_g, const uint8_t* codes_g,
const float* scales_g, const float* off_g, const SForm& form_u, const uint8_t* codes_u,
const float* scales_u, const float* off_u, float* out, int64_t n_in, int64_t n_out,
int threads_per_row, int swilu_kind, void* stream);
} // namespace strata::kernels
+176
View File
@@ -0,0 +1,176 @@
// include/strata/kernels/s_rowdev.cuh - ONE output row of an S-family GEMV, warp-collective.
//
// The V100 fusion work computes a row of `gate` and a row of `up` inside ONE kernel (llama.cpp's
// `mul_mat_gated` shape: both projections from one read of x, SwiGLU in the epilogue). For the fused and
// unfused pipelines to agree BITWISE each row must be accumulated exactly as the standalone kernel that
// would have produced it - same iteration space, same accumulator layout, same reduction tree, same
// expressions. These functions are those accumulation loops; `s_gemv_pair.cu` calls each one and
// `fusions_parity` checks the pair against the two standalone calls BITWISE, which is what keeps these
// copies honest (the standalone kernels are untouched and remain the reference).
#pragma once
#include <cuda_fp16.h>
#include <cuda_runtime.h>
#include <cstdint>
namespace strata::kernels {
/// ggml's `kvalues_iq4nl`, the table `s_gemv.cu` holds in `__constant__`.
__device__ __forceinline__ float iq4nl_value(int code) {
const signed char tbl[16] = {-127, -104, -83, -65, -49, -35, -22, -10,
1, 13, 25, 38, 53, 69, 89, 113};
return (float) tbl[code & 0x0F];
}
template <int CODE_BITS>
__device__ __forceinline__ float decode_row(int code, int bias, int codebook) {
if (codebook == 1) return iq4nl_value(code);
return (float) (code + bias);
}
/// the Q8_K activation element at `i` - `s_gemv.cu`'s `q8k_at`, verbatim
__device__ __forceinline__ float q8k_row_at(const uint8_t* __restrict__ x, long long i) {
const uint8_t* blk = x + (i / 256) * 292;
const float d = __ldg((const float*) blk);
const int8_t q = ((const int8_t*) (blk + 4))[i % 256];
return d * (float) q;
}
/// the Q8_0 activation element at `i` - `s_gemv.cu`'s `q8_0_at`, verbatim
__device__ __forceinline__ float q8_0_row_at(const uint8_t* __restrict__ x, long long i) {
const uint8_t* blk = x + (i / 32) * 34;
const float d = __half2float(__ushort_as_half(*(const uint16_t*) blk));
const int8_t q = ((const int8_t*) (blk + 2))[i % 32];
return d * (float) q;
}
/// `s_gemv_q8_split_kernel`'s row (`s_gemv.cu`), verbatim: 16 accumulators over `i = lane*16` stepping
/// `32*16`, the `(((acc0+acc1)+(acc2+acc3))+...)` tree, then the `__shfl_down_sync` tree. The reduced
/// value is valid in lane 0.
template <int CODE_BITS, bool Q8K>
__device__ __forceinline__ float row_s_q8(const uint8_t* __restrict__ x, const uint8_t* __restrict__ codes,
const float* __restrict__ scales, const float* __restrict__ offset,
long long n_in, long long o, int lane, int bias, int codebook,
int group_shift, int has_offset) {
constexpr int PER_BYTE = 8 / CODE_BITS;
const long long n_groups = n_in >> group_shift;
const long long codes_per_row = n_in / PER_BYTE;
const uint8_t* c = codes + o * codes_per_row;
const float* s = scales + o * n_groups;
const float* off = has_offset ? offset + o * n_groups : nullptr;
float acc0 = 0.0f, acc1 = 0.0f, acc2 = 0.0f, acc3 = 0.0f;
float acc4 = 0.0f, acc5 = 0.0f, acc6 = 0.0f, acc7 = 0.0f;
float acc8 = 0.0f, acc9 = 0.0f, acc10 = 0.0f, acc11 = 0.0f;
float acc12 = 0.0f, acc13 = 0.0f, acc14 = 0.0f, acc15 = 0.0f;
constexpr int QE = 16;
constexpr int QW = 4 * CODE_BITS / 8;
constexpr unsigned MASK = (1u << CODE_BITS) - 1u;
long long i = (long long) lane * QE;
for (; i + QE <= n_in; i += 32 * QE) {
const long long g = i >> group_shift;
const float d = s[g];
const float b = off ? off[g] : 0.0f;
const uint8_t* cp = c + i / PER_BYTE;
unsigned v, v2, v3, v4;
if (QW == 1) { v = cp[0]; v2 = cp[1]; v3 = cp[2]; v4 = cp[3]; }
else if (QW == 2) { v = *(const uint16_t*) cp; v2 = *(const uint16_t*) (cp + 2);
v3 = *(const uint16_t*) (cp + 4); v4 = *(const uint16_t*) (cp + 6); }
else { v = *(const uint32_t*) cp; v2 = *(const uint32_t*) (cp + 4);
v3 = *(const uint32_t*) (cp + 8); v4 = *(const uint32_t*) (cp + 12); }
const int blk_elems = Q8K ? 256 : 32;
const uint8_t* xb = x + (i / blk_elems) * (Q8K ? 292 : 34);
const int xi = (int) (i % blk_elems);
const float xd = Q8K ? __ldg((const float*) xb)
: __half2float(__ushort_as_half(*(const uint16_t*) xb));
const int8_t* xq = (const int8_t*) (xb + (Q8K ? 4 : 2)) + xi;
const float w0 = decode_row<CODE_BITS>((int) (v & MASK), bias, codebook) * d + b;
const float w1 = decode_row<CODE_BITS>((int) ((v >> CODE_BITS) & MASK), bias, codebook) * d + b;
const float w2 = decode_row<CODE_BITS>((int) ((v >> (2 * CODE_BITS)) & MASK), bias, codebook) * d + b;
const float w3 = decode_row<CODE_BITS>((int) ((v >> (3 * CODE_BITS)) & MASK), bias, codebook) * d + b;
const float w4 = decode_row<CODE_BITS>((int) (v2 & MASK), bias, codebook) * d + b;
const float w5 = decode_row<CODE_BITS>((int) ((v2 >> CODE_BITS) & MASK), bias, codebook) * d + b;
const float w6 = decode_row<CODE_BITS>((int) ((v2 >> (2 * CODE_BITS)) & MASK), bias, codebook) * d + b;
const float w7 = decode_row<CODE_BITS>((int) ((v2 >> (3 * CODE_BITS)) & MASK), bias, codebook) * d + b;
acc0 += w0 * (xd * (float) xq[0]);
acc1 += w1 * (xd * (float) xq[1]);
acc2 += w2 * (xd * (float) xq[2]);
acc3 += w3 * (xd * (float) xq[3]);
acc4 += w4 * (xd * (float) xq[4]);
acc5 += w5 * (xd * (float) xq[5]);
acc6 += w6 * (xd * (float) xq[6]);
acc7 += w7 * (xd * (float) xq[7]);
const float w8 = decode_row<CODE_BITS>((int) (v3 & MASK), bias, codebook) * d + b;
const float w9 = decode_row<CODE_BITS>((int) ((v3 >> CODE_BITS) & MASK), bias, codebook) * d + b;
const float w10 = decode_row<CODE_BITS>((int) ((v3 >> (2 * CODE_BITS)) & MASK), bias, codebook) * d + b;
const float w11 = decode_row<CODE_BITS>((int) ((v3 >> (3 * CODE_BITS)) & MASK), bias, codebook) * d + b;
const float w12 = decode_row<CODE_BITS>((int) (v4 & MASK), bias, codebook) * d + b;
const float w13 = decode_row<CODE_BITS>((int) ((v4 >> CODE_BITS) & MASK), bias, codebook) * d + b;
const float w14 = decode_row<CODE_BITS>((int) ((v4 >> (2 * CODE_BITS)) & MASK), bias, codebook) * d + b;
const float w15 = decode_row<CODE_BITS>((int) ((v4 >> (3 * CODE_BITS)) & MASK), bias, codebook) * d + b;
acc8 += w8 * (xd * (float) xq[8]);
acc9 += w9 * (xd * (float) xq[9]);
acc10 += w10 * (xd * (float) xq[10]);
acc11 += w11 * (xd * (float) xq[11]);
acc12 += w12 * (xd * (float) xq[12]);
acc13 += w13 * (xd * (float) xq[13]);
acc14 += w14 * (xd * (float) xq[14]);
acc15 += w15 * (xd * (float) xq[15]);
}
for (; i < n_in; i += 32 * QE) {
for (int k = 0; k < QE && i + k < n_in; ++k) {
const long long e = i + k;
const long long g = e >> group_shift;
const int code = (c[e / PER_BYTE] >> ((int) (e % PER_BYTE) * CODE_BITS)) & MASK;
acc0 += (decode_row<CODE_BITS>(code, bias, codebook) * s[g] + (off ? off[g] : 0.0f)) *
(Q8K ? q8k_row_at(x, e) : q8_0_row_at(x, e));
}
}
float acc = (((acc0 + acc1) + (acc2 + acc3)) + ((acc4 + acc5) + (acc6 + acc7))) +
(((acc8 + acc9) + (acc10 + acc11)) + ((acc12 + acc13) + (acc14 + acc15)));
for (int step = 16; step > 0; step >>= 1) acc += __shfl_down_sync(0xFFFFFFFFu, acc, step);
return acc;
}
/// `s2_gemv_q8_kernel`'s row (`s2_gemv_q8.cu`), verbatim: quads of four elements strided over
/// `threads_per_row` threads, four accumulators, then the shared-memory tree
/// `partial[tid] += partial[tid + step]`. `partial` must hold `threads_per_row` floats; the row value
/// lands in `partial[0]`.
__device__ __forceinline__ void row_s2_q8(const uint8_t* __restrict__ act, const uint8_t* __restrict__ codes,
const float* __restrict__ scales, long long n_in, long long o,
int tid, int threads_per_row, float* __restrict__ partial) {
const long long n_quads = n_in / 4;
const uint8_t* c = codes + o * n_quads;
const float* s = scales + o * (n_in / 64);
float a0 = 0.0f, a1 = 0.0f, a2 = 0.0f, a3 = 0.0f;
for (long long q = tid; q < n_quads; q += threads_per_row) {
const uint8_t byte = c[q];
const float d = s[q >> 4];
const long long ablk = (q * 4) / 32;
const uint8_t* blk = act + ablk * 34;
const uint16_t dbits = (uint16_t) (blk[0] | (blk[1] << 8));
const float dx = __half2float(__ushort_as_half(dbits));
const int8_t* xq = (const int8_t*) (blk + 2);
const int off = (int) ((q * 4) % 32);
const float w0 = (float) ((int) (byte & 3) - 1) * d;
const float w1 = (float) ((int) ((byte >> 2) & 3) - 1) * d;
const float w2 = (float) ((int) ((byte >> 4) & 3) - 1) * d;
const float w3 = (float) ((int) ((byte >> 6) & 3) - 1) * d;
a0 += w0 * ((float) xq[off + 0] * dx);
a1 += w1 * ((float) xq[off + 1] * dx);
a2 += w2 * ((float) xq[off + 2] * dx);
a3 += w3 * ((float) xq[off + 3] * dx);
}
partial[tid] = (a0 + a1) + (a2 + a3);
__syncwarp();
for (int step = threads_per_row / 2; step > 0; step >>= 1) {
if (tid < step) partial[tid] += partial[tid + step];
__syncwarp();
}
}
} // namespace strata::kernels
+42
View File
@@ -0,0 +1,42 @@
// include/strata/kernels/swiglu.cuh - the SwiGLU expressions, ONE copy each.
//
// The fusion work (V100) moves `silu(gate) * up` into the epilogue of the projection that computes `up`.
// For that to be bit-exact the fused epilogue must compute EXACTLY the expression the standalone kernel
// computed - same operations, same precision, same order. A second copy of the expression is a second
// thing to drift, so every caller (the standalone kernels and the fused epilogues) includes this file.
//
// THREE VARIANTS, because the engine really has three:
//
// `swilu_legacy` the `ref/moe.py` transcription: silu in DOUBLE then cast, multiply in float
// (`shared_expert.cu`'s `swiglu_kernel`, and the S2 expert path used to use this shape).
// `swilu_fast` the S2 expert path's float expression with `__expf`
// (`s2_expert_grouped.cu`'s `swiglu_kernel`).
// `swilu_native` the pinned CUDA contract: `__fdividef` and `__expf`
// (`shared_expert.cu`'s `native_swiglu_kernel`).
//
// Bit-exactness across translation units: both call sites compile this with the same CUDA flags (no
// `--use_fast_math` on the files that use the legacy and fast variants), the expressions are straight-line
// IEEE ops around one libdevice call, and the parity tests compare the fused and unfused pipelines bitwise.
#pragma once
#include <cuda_runtime.h>
namespace strata::kernels {
/// `out = (float)((double)g / (1.0 + exp(-(double)g))) * u` - `shared_expert.cu`'s `swiglu_kernel`.
__device__ __forceinline__ float swilu_legacy(float g, float u) {
const double x = (double) g;
return (float) (x / (1.0 + exp(-x))) * u;
}
/// `out = (g / (1.0f + __expf(-g))) * u` - `s2_expert_grouped.cu`'s `swiglu_kernel`.
__device__ __forceinline__ float swilu_fast(float g, float u) {
return (g / (1.0f + __expf(-g))) * u;
}
/// `out = __fdividef(g, 1.0f + __expf(-g)) * u` - `shared_expert.cu`'s `native_swiglu_kernel`.
__device__ __forceinline__ float swilu_native(float g, float u) {
return __fdividef(g, 1.0f + __expf(-g)) * u;
}
} // namespace strata::kernels
+78
View File
@@ -0,0 +1,78 @@
// include/strata/prefill/gdn_chunk.hpp - the chunked GDN prompt recurrence for Volta (sm_70), v100/gdn-chunk.
//
// The prompt recurrence (`gdn_recurrence`, src/prefill/kernels.cu) walks the chunk's tokens one by one; each
// token depends on the state left by the previous one, so the whole launch is a serial chain of T steps per
// (head, column-block). On a V100 that chain, not the flops, is what the GDN layers cost: the arithmetic is
// O(S^2) per token and S = 128.
//
// The chunked form (the FlashQLA "gdn-chunk" structure of 1Cat-vLLM, as ported for sm_70 in llama.cpp-v100's
// ggml/src/ggml-cuda/gdn-chunk-sm70*: cumsum -> kkt -> fwd, 64-token chunks) trades the token chain for a
// CHUNK chain: inside one 64-token chunk everything runs as dense matmuls and one triangular solve, and only
// the chunks stay in order (each needs the previous chunk's state). Same recurrence, different summation
// order - so FP32-level, NOT bit-exact against `gdn_recurrence` (the precedent: qsa_prompt_attn.hpp).
//
// THE MATH, derived from the recurrence in `strata/kernels/gdn.hpp` (per head; the state columns j are
// independent, so everything below is per column and can be written in matrix form over the i axis):
//
// a_t = exp(gate_t) (decay)
// W_t = a_t W_{t-1} + k_t delta_t^T (state, i x j)
// delta_t = beta_t (v_t - a_t k_t^T W_{t-1})
// o_t = q_t^T W_t (then * rsqrtf(S) by the caller-side convention)
//
// Unrolled over a chunk (c_t = inclusive cumsum of gate inside the chunk, sigma = c_63, W_in = state at the
// chunk's first token - one step per token, no approximations):
//
// W_t = exp(c_t) W_in + sum_{s<=t} exp(c_t-c_s) k_s delta_s^T
// x_t := a_t k_t^T W_{t-1}
// = exp(c_t) k_t^T W_in + sum_{s<t} exp(c_t-c_s) (k_t.k_s) delta_s
// delta_t = beta_t (v_t - x_t)
//
// which is one lower-triangular solve per chunk and column:
//
// (I + strict_lower(A)) delta = b A[t,s] = beta_t exp(c_t-c_s) (k_t.k_s) (s < t)
// b_t = beta_t ( v_t - exp(c_t) k_t^T W_in )
// o_t = exp(c_t) q_t^T W_in + sum_{s<=t} P[t,s] delta_s P[t,s] = exp(c_t-c_s) (q_t.k_s)
// W_out = exp(sigma) W_in + sum_s k_s exp(sigma-c_s) delta_s^T
//
// Every decay factor goes from a LATER token back to an EARLIER one - <= 1 for a real GDN gate (log-decay,
// negative) - so no exp of a positive argument is ever formed, delta stays O(beta v), and the solve is
// well-scaled in f32. (The reference's equivalent move is its cumsum/g_rev_exp pair; its kkt kernel keeps
// the matrix decay-free and lets fwd multiply the mask in - this implementation bakes the decay into A and P
// in the kkt stage, which is the same numbers with one less pass.)
//
// The three kernels here are the same three stages as the reference:
//
// gdn_chunk_cumsum_kernel g_cumsum[t][h] = cumsum of gate over the chunk's 64 tokens
// gdn_chunk_kkt_kernel A and P = (q_t.k_s) per (chunk, head), one block each
// gdn_chunk_fwd_kernel one block per (head, 32 value-columns) over ALL chunks: the state slice lives in
// registers across chunks (chunk-serial scan), each chunk is a batch of matmuls
//
// Kernels are hand-written CUDA, FP32 throughout (the q/k staging through FP16 and the m8n8k4/wmma of the
// reference's TileLang output are a later step; nothing here depends on TileLang). Dispatch is a runtime
// compute-capability check in `gdn_recurrence` - sm_80 and up keep the old recurrence unless STRATA_GDN_CHUNK
// overrides it.
#pragma once
#include <cstdint>
namespace strata::prefill {
/// Is the chunked recurrence worth dispatching to on this device? Volta (cc 7.0) only - that is where the
/// token chain hurts and where this was measured; every other architecture keeps the existing recurrence.
bool gdn_chunk_available();
/// The chunked recurrence over `T` tokens (T a multiple of 64 - the caller keeps `T % 64` for the recurrent
/// kernel; `gdn_recurrence` does this itself). Same buffers and conventions as `gdn_recurrence`, minus the
/// output norm, which the caller runs over the whole chunk as before:
///
/// state (S, h_v, S) f32, j fastest, updated in place
/// h [T, C] post-conv, q/k L2-normalised rows (q NOT scaled by 1/sqrt(S); this writes o/sqrt(S))
/// gate [T, h_v] the PRE-exp gate; beta [T, h_v] already sigmoided
/// oc [T, h_v, S] the un-normed o * rsqrtf(S) - what `gdn_rec_cols_*` writes as `y` before the norm
///
/// FP32-level, not bit-exact against the recurrence: the same recurrence in a different summation order.
/// Scratch (A, P and the cumsum) is a grow-only static workspace, segmented so a 32k prompt does not size it.
void gdn_chunk_recurrence(float* state, const float* h, const float* gate, const float* beta, float* oc,
int64_t T, void* stream);
} // namespace strata::prefill
+2
View File
@@ -83,6 +83,8 @@ void route(const float* logits, int32_t* ids, float* weights, int64_t T, int64_t
void blob_dequant(const uint8_t* blob, uint16_t* gu16, uint16_t* down16, void* stream);
/// h16[n, r] = fp16(silu(gu[n, 2r]) * gu[n, 2r + 1]) (the interleaved expert gate/up)
void swiglu_interleaved(const float* gu, uint16_t* h16, int64_t n, void* stream);
/// the Volta prompt experts: SwiGLU of gate/up rows (gate first, or interleaved) to FP16, saturated like swiglu_interleaved
void swiglu_split_f16(const float* gu, uint16_t* h16, int64_t rows, int n_ff, bool interleaved, void* stream);
/// h16[n, r] = fp16(silu(g[n, r]) * u[n, r]) (the shared expert, gate and up separate, width 640)
void swiglu_pair(const float* g, const float* u, uint16_t* h16, int64_t n, void* stream);
/// dst[i] = src[i] for n int32s, as a kernel: either side may be mapped host memory, and the copy never waits
+83 -6
View File
@@ -12,6 +12,7 @@
#include "strata/kernels/kv_q4.hpp"
#include "strata/kernels/kv_q8.hpp"
#include "strata/kernels/quantize_act.hpp"
#include "strata/kernels/fuse_decode.hpp"
#include "strata/kernels/rope.hpp"
#include "strata/kernels/router_top10.hpp"
#include "strata/kernels/s2_gemv_q8.hpp"
@@ -106,6 +107,25 @@ void project_bf16(const float* x, const uint16_t* x_bf16, const uint16_t* weight
else if (split) bf16_gemv_split(x_bf16, weights, out, n_in, n_out, TPR, stream);
else bf16_gemv(x_bf16, weights, out, n_in, n_out, stream);
}
#if defined(STRATA_EXPERIMENTAL_SM60)
// TWO BF16 projections of the SAME x in ONE kernel (`ssm_alpha`/`ssm_beta`, `indexer.q`/`indexer.k`).
// `bf16_gemv_pair` reproduces the warp-per-row accumulation, which is what `bf16_gemv_split` at TPR 32
// always runs and what plain `bf16_gemv` runs at n_out >= 64 - below that the plain entry uses the naive
// one-thread-per-row sum and the pair would round differently, so those shapes keep two calls.
void project_bf16_pair(const float* x, const uint16_t* x_bf16, const uint16_t* w1, float* o1, int64_t n_out1,
const uint16_t* w2, float* o2, int64_t n_out2, int64_t n_in, bool split, void* stream) {
using namespace strata::kernels;
if (native_bf16_projections) {
bf16_gemv_fp32_mmvf(x, w1, o1, n_in, n_out1, stream);
bf16_gemv_fp32_mmvf(x, w2, o2, n_in, n_out2, stream);
} else if (split || (n_out1 >= 64 && n_out2 >= 64)) {
bf16_gemv_pair(x_bf16, w1, o1, n_out1, w2, o2, n_out2, n_in, stream);
} else {
bf16_gemv(x_bf16, w1, o1, n_in, n_out1, stream);
bf16_gemv(x_bf16, w2, o2, n_in, n_out2, stream);
}
}
#endif
///< threads per row for the row-split GEMVs.
/// **MEASURED, NOT ASSUMED, AND 64 IS NOT BETTER.** `dense_pass.exe` drives the same split kernels at
/// threads_per_row 64 and reports 248.5 GB/s, so matching it looked like free performance. It is not:
@@ -241,9 +261,16 @@ const float* conv_kernel = (const float*) w_conv->data; const float* ssm_norm
st_begin(layer, 8, stream);
// Plan v0.3 P3: the canonical activation images only when a canonical projection reads them.
if (!w_qkv->native_data || !w_gate->native_data) {
#if defined(STRATA_EXPERIMENTAL_SM60)
if (strata::kernels::fuse_decode()) {
quantize_act_images(mixed, g.n_embd, b.x_q8_0, b.x_q8k, nullptr, stream); // ONE pass, was two kernels
} else
#endif
{
quantize_q8_K(mixed, b.x_q8k, g.n_embd, stream);
quantize_q8_0(mixed, b.x_q8_0, g.n_embd, stream);
}
}
st_end(layer, 8, stream);
// ---- 2. qkv = wqkv @ x, with the activation THIS layer's `attn_qkv` asks for
st_begin(layer, 9, stream); if (!gemv_quantized(*w_qkv, p_qkv, f_qkv, b.x_q8_0, b.x_q8k, b.qkv, g.n_embd, C, v.name("attn_qkv.weight"), stream, err, mixed)) return false; st_end(layer, 9, stream);
@@ -296,9 +323,17 @@ st_begin(layer, 12, stream);
(int) g.n_embd, (int) g.ssm_v_heads, stream);
} else {
if (!native_bf16_projections) f32_to_bf16_bulk(mixed, b.x_bf16, g.n_embd, stream);
#if defined(STRATA_EXPERIMENTAL_SM60)
if (strata::kernels::fuse_decode()) {
project_bf16_pair(mixed, b.x_bf16, (const uint16_t*) w_alpha->data, b.alpha, g.ssm_v_heads,
(const uint16_t*) w_beta->data, b.beta, g.ssm_v_heads, g.n_embd, true, stream);
} else
#endif
{
project_bf16(mixed, b.x_bf16, (const uint16_t*) w_alpha->data, b.alpha, g.n_embd, g.ssm_v_heads, true, stream);
project_bf16(mixed, b.x_bf16, (const uint16_t*) w_beta->data, b.beta, g.n_embd, g.ssm_v_heads, true, stream);
}
}
if (!fused_pre) try {
if (native_gdn_enabled()) {
native_gdn_beta_gate(b.beta, g.ssm_v_heads, stream);
@@ -336,8 +371,15 @@ st_end(layer, 14, stream);
// ---- 8. out = ssm_out @ y, whose activation is whatever THIS layer's `ssm_out` asks for
st_begin(layer, 15, stream);
if (!w_out->native_data) {
#if defined(STRATA_EXPERIMENTAL_SM60)
if (strata::kernels::fuse_decode()) {
quantize_act_images(b.y, g.ssm_value_dim, b.y_q8_0, b.y_q8k, nullptr, stream); // ONE pass, was two
} else
#endif
{
quantize_q8_K(b.y, b.y_q8k, g.ssm_value_dim, stream);
quantize_q8_0(b.y, b.y_q8_0, g.ssm_value_dim, stream);
}
} if (!gemv_quantized(*w_out, p_out, f_out, b.y_q8_0, b.y_q8k, out, g.ssm_value_dim, g.n_embd, v.name("ssm_out.weight"), stream, err, b.y)) return false; st_end(layer, 15, stream); return true;}
// ================================ the MoE block ================================
uint64_t moe_buffers_bytes(const ModelGeometry& g, int64_t k) { const uint64_t parts[] = { (uint64_t) g.n_embd * 2,
@@ -435,11 +477,22 @@ if (w_ginp->kind != WeightKind::Bf16InF32) { err = v.name("ffn_gate_inp_s
// the rest, `ffn_up_shexp` Q2_0 on 13, and `ffn_down_shexp` is LEGACY in every layer (IQ4_NL/Q4_0/Q5_0/
// Q8_0/Q2_0, `n_in` 640 so Q8_K is impossible). So BOTH quantized images of the activation are produced
// and each projection takes the one its own form asks for.
f32_to_bf16_bulk(x, b.x_bf16, g.n_embd, stream);
// ONE pass over `x` produces the bf16 image and both quantized images (was three kernels): which quantized
// one is wanted is a property of the TENSOR and the pack mixes them by layer, so both are produced.
if (!w_sgate->native_data || !w_sup->native_data) {
#if defined(STRATA_EXPERIMENTAL_SM60)
if (strata::kernels::fuse_decode()) {
quantize_act_images(x, g.n_embd, b.x_q8_0, b.x_q8k, b.x_bf16, stream); // ONE pass, was three kernels
} else
#endif
{
f32_to_bf16_bulk(x, b.x_bf16, g.n_embd, stream);
quantize_q8_K(x, b.x_q8k, g.n_embd, stream);
quantize_q8_0(x, b.x_q8_0, g.n_embd, stream);
}
} else {
f32_to_bf16_bulk(x, b.x_bf16, g.n_embd, stream);
}
NativeSharedWeights native;
native.gate_type = w_sgate->native_type; native.gate_data = w_sgate->native_data;
native.up_type = w_sup->native_type; native.up_data = w_sup->native_data;
@@ -1094,11 +1147,21 @@ struct Req { const char* suf; }; const WeightRef* w_idxk = v.get("indexer.k_p
// Reading one as f32 would walk 2x its length inside the arena without faulting.
if (w_idxk->kind != WeightKind::Bf16InF32 || w_idxq->kind != WeightKind::Bf16InF32) { err = v.name("indexer.*_proj.weight") + " must be engine form 1 (bf16); they are " + std::to_string((int) w_idxk->kind) + " and " + std::to_string((int) w_idxq->kind); return false; }
// ---- 1. the three activation formats, once each
if (!w_attnk->native_data || !w_attnv->native_data || !w_attnq->native_data) {
bool images_fused = false;
#if defined(STRATA_EXPERIMENTAL_SM60)
if (strata::kernels::fuse_decode() && (!w_attnk->native_data || !w_attnv->native_data || !w_attnq->native_data)) {
quantize_act_images(x, g.n_embd, b.x_q8_0, b.x_q8k,
native_bf16_projections ? nullptr : b.x_bf16, stream); // ONE pass, was two or three
images_fused = true;
}
#endif
if (!images_fused) {
if (!w_attnk->native_data || !w_attnv->native_data || !w_attnq->native_data) {
quantize_q8_K(x, b.x_q8k, g.n_embd, stream);
quantize_q8_0(x, b.x_q8_0, g.n_embd, stream);
}
if (!native_bf16_projections) f32_to_bf16_bulk(x, b.x_bf16, g.n_embd, stream);
}
// ---- 2. the step state: ONE H2D carries every per-token count the kernels need. Nothing below passes a
// per-token scalar as an argument, which is what keeps this layer capturable.
//
@@ -1115,8 +1178,20 @@ if (!w_attnk->native_data || !w_attnv->native_data || !w_attnq->native_data) {
strata::kernels::copy_i32_from_mapped(st.pos_dev, m_pos, g.n_head, stream);
} else
if (cudaMemcpyAsync(st.step, st.host_step, qsa_step_bytes(), cudaMemcpyHostToDevice, (cudaStream_t) stream) != cudaSuccess || cudaMemcpyAsync(st.pos_dev, st.host_pos, (size_t) g.n_head * 4, cudaMemcpyHostToDevice, (cudaStream_t) stream) != cudaSuccess) { err = "qsa_layer: the step-state upload failed"; return false; } }
// ---- 3. the indexer's RAW key: appended before any norm, pooled later once per block
project_bf16(x, b.x_bf16, (const uint16_t*) w_idxk->data, b.idx_raw, g.n_embd, g.idx_key_dim, false, stream);
// ---- 3. the indexer's RAW key (and, with the V100 switch, its QUERY in the same kernel; was two launches)
bool idx_pair = false;
#if defined(STRATA_EXPERIMENTAL_SM60)
if (strata::kernels::fuse_decode()) {
// two BF16 projections of the same x in ONE kernel: the query is needed only at step 7 and nothing in between
// touches it, so computing it here changes no order that matters; `idx_raw` is still appended at step 5.
project_bf16_pair(x, b.x_bf16, (const uint16_t*) w_idxk->data, b.idx_raw, g.idx_key_dim,
(const uint16_t*) w_idxq->data, b.q_idx, g.idx_q_heads * g.idx_key_dim, g.n_embd,
false, stream);
idx_pair = true;
}
#endif
if (!idx_pair)
project_bf16(x, b.x_bf16, (const uint16_t*) w_idxk->data, b.idx_raw, g.n_embd, g.idx_key_dim, false, stream);
// ---- 4. K and V, in Q8_K, then norm and rotate K only
SForm f_k, f_v, f_o, f_q; if (!sform_of(*w_attnk, f_k, v.name("attn_k.weight"), err)) return false; if (!sform_of(*w_attnv, f_v, v.name("attn_v.weight"), err)) return false; if (!sform_of(*w_attno, f_o, v.name("attn_output.weight"), err)) return false; if (!sform_of(*w_attnq, f_q, v.name("attn_q.weight"), err)) return false; Planes p_k, p_v, p_o, p_q; if (!plane_ptrs(*w_attnk, v.name("attn_k.weight"), p_k, err)) return false; if (!plane_ptrs(*w_attnv, v.name("attn_v.weight"), p_v, err)) return false; if (!plane_ptrs(*w_attno, v.name("attn_output.weight"), p_o, err)) return false; if (!plane_ptrs(*w_attnq, v.name("attn_q.weight"), p_q, err)) return false;
// k and v, with the activation THIS layer's tensors ask for. Both are K-quants in every QSA layer of this
@@ -1167,8 +1242,10 @@ if (!gemv_quantized(*w_attnq, p_q, f_q, b.x_q8_0, b.x_q8k, b.q_full, g.n_embd, g
// the norm and the rotation see whole rows. A 2-D copy is a memcpy node, which captures (`pinned_capture`
// case A) and needs no kernel.
if (cudaMemcpy2DAsync(b.qcur, (size_t) g.head_dim * 4, b.q_full, (size_t) g.head_dim * 2 * 4, (size_t) g.head_dim * 4, (size_t) g.n_head, cudaMemcpyDeviceToDevice, (cudaStream_t) stream) != cudaSuccess) { err = "qsa_layer: the q/gate split failed"; return false; } if (!normalize_rotate(b.qcur, w_qn, (int) g.n_head, (int) g.head_dim)) return false;
// ---- 7. the indexer's query: BF16, then norm and rotate
project_bf16(x, b.x_bf16, (const uint16_t*) w_idxq->data, b.q_idx, g.n_embd, g.idx_q_heads * g.idx_key_dim, false, stream);
// ---- 7. the indexer's query: with the V100 switch it was projected at step 3 (paired with the raw key);
// the trunk projects it here. Either way, norm and rotate it now.
if (!idx_pair) project_bf16(x, b.x_bf16, (const uint16_t*) w_idxq->data, b.q_idx, g.n_embd, g.idx_q_heads * g.idx_key_dim,
false, stream);
if (!normalize_rotate(b.q_idx, w_iqn, (int) g.idx_q_heads, (int) g.idx_key_dim)) return false;
// ---- 8. score, select, gather, attend. `max_blocks` and `cap` are CAPACITIES from the state, not this
// token's counts: a grid or a shared-memory size that follows the sequence length is baked into a captured
+3
View File
@@ -18,6 +18,7 @@ NativeHead::~NativeHead() {
void NativeHead::unload() {
if (weights_) strata::kernels::native_q6_k_unpack(weights_);
if (weights_) strata::kernels::native_q8_0_sm60_release(weights_);
if (scratch_) cudaFree(scratch_);
if (weights_) cudaFree(weights_);
scratch_ = nullptr;
@@ -73,6 +74,8 @@ bool NativeHead::load(const std::vector<std::string>& shards, int64_t n_in, int6
type_ = (int) tensor->type;
if (type_ == 14 && strata::kernels::native_q6_k_packed_enabled()) // STRATA_Q6_PACKED=1
strata::kernels::native_q6_k_pack(weights_, n_in_, n_out_, "output head");
if (type_ == 8) // STRATA_Q8_SM60=1 (a no-op otherwise); the MTP draft head reads the same matrix
strata::kernels::native_q8_0_sm60_pack(weights_, n_in_, n_out_, "output head");
return true;
} catch (const std::exception& error) {
err = std::string("native head: ") + error.what();
+1 -1
View File
@@ -2207,7 +2207,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
// Greedy, the default, is recorded here as before (no extra launch or sync per window). A request that
// samples or penalizes is sampled again host-side after the replay (run()) with its own parameters and a
// fresh draw counter: a captured sampler would bake them in and replay the same draws forever.
if (argmax_rows_wanted()) { // sm_80 to sm_89: the pick over many blocks a row (bitwise the one-block kernel's)
if (argmax_rows_wanted()) { // sm_80 to sm_89 (sm_7x opt-in): the pick over many blocks a row (bitwise the one-block kernel's)
argmax_rows(head_logits_, T, (int) n_vocab_, arg_scratch_, m_out_, cs);
} else {
SamplerParams sp;
+48
View File
@@ -65,6 +65,40 @@ __global__ void bf16_gemv_split_kernel(const uint16_t* __restrict__ x, const uin
if (t == 0) y[o] = scratch[0];
}
/// TWO weight matrices from one read of x - llama.cpp's `*_mul_mat_multi` shape. One warp computes row `o`
/// of `w1` and row `o` of `w2` with two independent accumulators over the SAME lane-strided loop, so each
/// accumulator sees the addend sequence its standalone `bf16_gemv_warp_kernel` run gave it: bitwise equal
/// (checked by `bf16_gemv_pair_parity`). Rows past a matrix's `n_out` skip that accumulator only.
__global__ void bf16_gemv_pair_warp_kernel(const uint16_t* __restrict__ x, const uint16_t* __restrict__ w1,
float* __restrict__ y1, long long n_out1,
const uint16_t* __restrict__ w2, float* __restrict__ y2,
long long n_out2, long long n_in) {
const int warps_per_block = (int) (blockDim.x >> 5);
const long long o = (long long) blockIdx.x * warps_per_block + (threadIdx.x >> 5);
const int lane = threadIdx.x & 31;
const long long n_out = n_out1 > n_out2 ? n_out1 : n_out2;
if (o >= n_out) return;
const int run1 = o < n_out1, run2 = o < n_out2;
const uint16_t* r1 = w1 + o * n_in;
const uint16_t* r2 = w2 + o * n_in;
float acc1 = 0.0f, acc2 = 0.0f;
for (long long i = lane; i < n_in; i += 32) {
const float xv = f32_from_bf16(x[i]);
if (run1) acc1 += xv * f32_from_bf16(r1[i]);
if (run2) acc2 += xv * f32_from_bf16(r2[i]);
}
if (run1) {
float a = acc1;
for (int off = 16; off > 0; off >>= 1) a += __shfl_down_sync(0xFFFFFFFFu, a, off);
if (lane == 0) y1[o] = a;
}
if (run2) {
float a = acc2;
for (int off = 16; off > 0; off >>= 1) a += __shfl_down_sync(0xFFFFFFFFu, a, off);
if (lane == 0) y2[o] = a;
}
}
inline void finish(void* stream, const char* what) {
const cudaError_t e = cudaGetLastError();
if (e != cudaSuccess) {
@@ -114,6 +148,20 @@ void bf16_gemv(const uint16_t* x, const uint16_t* w, float* y, int64_t n_in, int
finish(stream, "bf16_gemv");
}
void bf16_gemv_pair(const uint16_t* x, const uint16_t* w1, float* y1, int64_t n_out1, const uint16_t* w2,
float* y2, int64_t n_out2, int64_t n_in, void* stream) {
if (n_in <= 0 || (n_out1 <= 0 && n_out2 <= 0)) return;
// THE PAIR KERNEL IS THE WARP-PER-ROW ACCUMULATION on both sides, so it is bitwise what
// `bf16_gemv` (n_out >= 64) and `bf16_gemv_split` at tpr 32 produced. Callers whose standalone path
// was the NAIVE kernel (a small `n_out` with the plain entry) must not use this.
const int warps = THREADS / 32;
const long long n_out = n_out1 > n_out2 ? n_out1 : n_out2;
const unsigned grid = (unsigned) ((n_out + warps - 1) / warps);
bf16_gemv_pair_warp_kernel<<<grid, THREADS, 0, (cudaStream_t) stream>>>(
x, w1, y1, n_out1, w2, y2, n_out2, n_in);
finish(stream, "bf16_gemv_pair");
}
void bf16_gemv_split(const uint16_t* x, const uint16_t* w, float* y, int64_t n_in, int64_t n_out,
int threads_per_row, void* stream) {
if (n_in <= 0 || n_out <= 0) return;
+4 -2
View File
@@ -1161,7 +1161,7 @@ bool gr_down_max4() {
return on;
}
// the split norm with registers (gr_norm_split_fast_kernel): gfx12 only until another arch is measured;
// the split norm with registers (gr_norm_split_fast_kernel): on by default on gfx12; CUDA opt-in (measured on sm_70 only);
// STRATA_GR_NORM_FAST=0 / 1 forces it off / on
bool norm_fast_on() {
#if defined(__HIPCC__)
@@ -1176,7 +1176,9 @@ bool norm_fast_on() {
}
return per_dev[dev] == 2;
#else
return false;
// CUDA: opt-in with STRATA_GR_NORM_FAST=1 (measured on sm_70 only)
static const bool on = [] { const char* e = std::getenv("STRATA_GR_NORM_FAST"); return e != nullptr && std::atoi(e) != 0; }();
return on;
#endif
}
+519 -25
View File
@@ -807,7 +807,7 @@ template<int TY> struct Split;
// per-entry ones, which call Fmt<TY>::dot per column exactly as before #242 (the launchers test kSplit at compile
// time, so the multi kernels are never instantiated for a type without a Split).
template<int TY> inline constexpr bool kSplit = false;
template<int TY> inline constexpr bool kStageIqGrid = (TY == 16 || TY == 17 || TY == 22 || TY == 29);
template<int TY> inline constexpr bool kStageIqGrid = (TY == 16 || TY == 17 || TY == 18 || TY == 21 || TY == 22 || TY == 29);
template<> inline constexpr bool kSplit<16> = true;
template<> struct Split<16> { // IQ2_XXS
@@ -941,18 +941,25 @@ template<> struct Split<18> { // IQ3_XXS
const int2 q3_packed = make_int2(get_int_b2(bq3->qs, iqs), get_int_b2(bq3->qs, iqs + 1));
const uint8_t* q3 = (const uint8_t*) &q3_packed;
const uint32_t aux32 = get_int_b2(bq3->qs, QK_K / 16 + iqs / 2);
const uint32_t* grid_lut; // the same 256 words either way (expdec stages them)
if constexpr (STAGE_GRID) grid_lut = s_grid;
else grid_lut = iq3xxs_grid;
const uint32_t* grid = STAGE_GRID ? s_grid : iq3xxs_grid;
W r;
#pragma unroll
for (int l0 = 0; l0 < 8; l0 += 2) {
const int2 grid_pos = make_int2(grid_lut[q3[l0 + 0]], grid_lut[q3[l0 + 1]]);
const uint32_t signs = unpack_ksigns(aux32 >> (7 * l0 / 2));
const int signs0 = __vcmpne4(signs & 0x08040201, 0);
r.g[l0 + 0] = __vsub4(grid_pos.x ^ signs0, signs0);
const int signs1 = __vcmpne4(signs & 0x80402010, 0);
r.g[l0 + 1] = __vsub4(grid_pos.y ^ signs1, signs1);
const int2 grid_pos = make_int2(grid[q3[l0 + 0]], grid[q3[l0 + 1]]);
if constexpr (STAGE_GRID) {
// The staged tables hold one mask per 7-bit sign field; bit 7 of the field is the next group's
// first sign, which unpack_ksigns cancels, so masking it off is the same value.
const uint32_t v = (aux32 >> (7 * l0 / 2)) & 0x7f;
const uint32_t ml = s_grid[256 + v], mh = s_grid[384 + v];
r.g[l0 + 0] = (int) ((grid_pos.x ^ ml) + (ml & 0x01010101u));
r.g[l0 + 1] = (int) ((grid_pos.y ^ mh) + (mh & 0x01010101u));
} else {
const uint32_t signs = unpack_ksigns(aux32 >> (7 * l0 / 2));
const int signs0 = __vcmpne4(signs & 0x08040201, 0);
r.g[l0 + 0] = __vsub4(grid_pos.x ^ signs0, signs0);
const int signs1 = __vcmpne4(signs & 0x80402010, 0);
r.g[l0 + 1] = __vsub4(grid_pos.y ^ signs1, signs1);
}
}
r.ls = aux32 >> 28;
r.dw = __half2float(bq3->d);
@@ -986,18 +993,24 @@ template<> struct Split<21> { // IQ3_S
const int qh = bq3->qh[iqs / 2];
const int signs_packed_32 = get_int_b2(bq3->signs, iqs / 2);
const uint8_t* signs_packed_8 = (const uint8_t*) &signs_packed_32;
const uint32_t* grid_lut; // the same 512 words either way (expdec stages them)
if constexpr (STAGE_GRID) grid_lut = s_grid;
else grid_lut = iq3s_grid;
const uint32_t* grid = STAGE_GRID ? s_grid : iq3s_grid;
W r;
#pragma unroll
for (int l0 = 0; l0 < 8; l0 += 2) {
const int2 grid_pos = make_int2(grid_lut[qs[l0 + 0] | ((qh << (8 - l0)) & 0x100)],
grid_lut[qs[l0 + 1] | ((qh << (7 - l0)) & 0x100)]);
const int signs0 = __vcmpne4(((signs_packed_8[l0 / 2] & 0x03) << 7) | ((signs_packed_8[l0 / 2] & 0x0C) << 21), 0x00000000);
const int signs1 = __vcmpne4(((signs_packed_8[l0 / 2] & 0x30) << 3) | ((signs_packed_8[l0 / 2] & 0xC0) << 17), 0x00000000);
r.g[l0 + 0] = __vsub4(grid_pos.x ^ signs0, signs0);
r.g[l0 + 1] = __vsub4(grid_pos.y ^ signs1, signs1);
const int2 grid_pos = make_int2(grid[qs[l0 + 0] | ((qh << (8 - l0)) & 0x100)],
grid[qs[l0 + 1] | ((qh << (7 - l0)) & 0x100)]);
if constexpr (STAGE_GRID) {
// The staged tables hold the byte masks of a sign byte's bits 0-3 and 4-7; every iq3s_grid byte is
// odd, so (g ^ mask) + (mask & 0x01010101) negates the masked bytes with no carry into the next.
const uint32_t ml = s_grid[512 + signs_packed_8[l0 / 2]], mh = s_grid[768 + signs_packed_8[l0 / 2]];
r.g[l0 + 0] = (int) (((uint32_t) grid_pos.x ^ ml) + (ml & 0x01010101u));
r.g[l0 + 1] = (int) (((uint32_t) grid_pos.y ^ mh) + (mh & 0x01010101u));
} else {
const int signs0 = __vcmpne4(((signs_packed_8[l0 / 2] & 0x03) << 7) | ((signs_packed_8[l0 / 2] & 0x0C) << 21), 0x00000000);
const int signs1 = __vcmpne4(((signs_packed_8[l0 / 2] & 0x30) << 3) | ((signs_packed_8[l0 / 2] & 0xC0) << 17), 0x00000000);
r.g[l0 + 0] = __vsub4(grid_pos.x ^ signs0, signs0);
r.g[l0 + 1] = __vsub4(grid_pos.y ^ signs1, signs1);
}
}
r.ls = 1 + 2 * ((bq3->scales[iqs / 4] >> ((iqs << 1) & 0x04)) & 0x0F);
r.dw = __half2float(bq3->d);
@@ -1419,6 +1432,36 @@ __device__ __forceinline__ void row_dot_80_sub16(const uint8_t* row, const block
}
}
// The sign-mask tables that follow the codebook words in a staged IQ3_XXS / IQ3_S table (see stage_iq_grid): the byte
// masks of every 7-bit sign field (IQ3_XXS, 2 x 128 words at +256) and of a sign byte's bits 0-3 and 4-7 (IQ3_S, 2 x 256
// words at +512). Split<18>::load<true> and Split<21>::load<true> read them, so every kernel that stages these two
// codebooks (the default kernels through stage_iq_grid, the STRATA_EXPDEC window kernels through EdGrid) fills them too.
__device__ __forceinline__ void stage_iq3xxs_masks(uint32_t* s_buf, int tid, int nthreads) {
for (int u = tid; u < 128; u += nthreads) {
const uint32_t s = (uint32_t) u | ((__popc((uint32_t) u) & 1u) << 7); // 8th sign = parity of the 7
uint32_t ml = 0, mh = 0;
#pragma unroll
for (int i = 0; i < 4; ++i) {
ml |= ((s >> i) & 1u) * (0xffu << (8 * i));
mh |= ((s >> (4 + i)) & 1u) * (0xffu << (8 * i));
}
s_buf[256 + u] = ml;
s_buf[384 + u] = mh;
}
}
__device__ __forceinline__ void stage_iq3s_masks(uint32_t* s_buf, int tid, int nthreads) {
for (int u = tid; u < 256; u += nthreads) {
uint32_t ml = 0, mh = 0;
#pragma unroll
for (int i = 0; i < 4; ++i) {
ml |= (((uint32_t) u >> i) & 1u) * (0xffu << (8 * i));
mh |= (((uint32_t) u >> (4 + i)) & 1u) * (0xffu << (8 * i));
}
s_buf[512 + u] = ml;
s_buf[768 + u] = mh;
}
}
template<int TY, bool STAGE_GRID = kStageIqGrid<TY>>
__device__ __forceinline__ const uint32_t* stage_iq_grid(uint32_t* s_buf, int tid, int nthreads) {
if constexpr (!STAGE_GRID) {
@@ -1447,6 +1490,25 @@ __device__ __forceinline__ const uint32_t* stage_iq_grid(uint32_t* s_buf, int ti
for (int i = tid; i < 1024; i += nthreads) dst[i] = src[i];
__syncthreads();
return s_buf;
} else if constexpr (TY == 18) {
// 256 codebook words, then two 128-word tables of the per-byte sign masks (signs 0-3, signs 4-7). A
// mask depends only on the 7 bits it is unpacked from, and iq3xxs_grid's bytes are all >= 4, so the
// consumer applies it as (g ^ mask) + (mask & 0x01010101): a negate per set byte, with no carry into
// the next. One pass per block replaces the per-lookup unpack_ksigns / __vcmpne4 / __vsub4 chain.
// Ported from shinbunbun/llama-cpp-p100-patches (MIT), patches 29 `mmvq-iq3xxs-grid-smem` and 30
// `mmvq-ksigns-smem`, measured there on a Tesla P100 (sm_60).
for (int i = tid; i < 256; i += nthreads) s_buf[i] = iq3xxs_grid[i];
stage_iq3xxs_masks(s_buf, tid, nthreads);
__syncthreads();
return s_buf;
} else if constexpr (TY == 21) {
// 512 codebook words, then two 256-word tables: the byte masks of a sign byte's bits 0-3 and of its bits
// 4-7 (IQ3_S stores one sign byte per 8 values). As for IQ3_XXS, one pass per block replaces the
// per-lookup __vcmpne4 / __vsub4 chain, and the codebook reads leave global memory.
for (int i = tid; i < 512; i += nthreads) s_buf[i] = iq3s_grid[i];
stage_iq3s_masks(s_buf, tid, nthreads);
__syncthreads();
return s_buf;
} else {
return nullptr;
}
@@ -1454,7 +1516,7 @@ __device__ __forceinline__ const uint32_t* stage_iq_grid(uint32_t* s_buf, int ti
template<int TY, bool STAGE_GRID = kStageIqGrid<TY>>
struct IqGridWords {
static constexpr int value = !STAGE_GRID ? 4 : (TY == 22 || TY == 29) ? 2048 : (TY == 17) ? 1024 : (TY == 16) ? 512 : 4;
static constexpr int value = !STAGE_GRID ? 4 : (TY == 22 || TY == 29) ? 2048 : (TY == 17 || TY == 21) ? 1024 : (TY == 16 || TY == 18) ? 512 : 4;
};
// mmvq_kernel with the columns taken NC at a time. After warp_sum every lane holds the same sum, so lane c stores
@@ -1900,10 +1962,17 @@ template<> struct EdGrid<17> { static constexpr int words = 1024;
__device__ static void copy(uint32_t* s, int tid) { const uint2* src = (const uint2*) iq2xs_grid; uint2* dst = (uint2*) s; for (int i = tid; i < 512; i += 256) dst[i] = src[i]; } };
template<> struct EdGrid<22> { static constexpr int words = 2048;
__device__ static void copy(uint32_t* s, int tid) { const uint2* src = (const uint2*) iq2s_grid; uint2* dst = (uint2*) s; for (int i = tid; i < 1024; i += 256) dst[i] = src[i]; } };
template<> struct EdGrid<18> { static constexpr int words = 256;
__device__ static void copy(uint32_t* s, int tid) { for (int i = tid; i < 256; i += 256) s[i] = iq3xxs_grid[i]; } };
template<> struct EdGrid<21> { static constexpr int words = 512;
__device__ static void copy(uint32_t* s, int tid) { for (int i = tid; i < 512; i += 256) s[i] = iq3s_grid[i]; } };
// (IQ3_XXS / IQ3_S: the codebook and, behind it, the sign-mask tables Split<TG>::load<true> reads - stage_iq_grid's layout)
template<> struct EdGrid<18> { static constexpr int words = 512;
__device__ static void copy(uint32_t* s, int tid) {
for (int i = tid; i < 256; i += 256) s[i] = iq3xxs_grid[i];
stage_iq3xxs_masks(s, tid, 256);
} };
template<> struct EdGrid<21> { static constexpr int words = 1024;
__device__ static void copy(uint32_t* s, int tid) {
for (int i = tid; i < 512; i += 256) s[i] = iq3s_grid[i];
stage_iq3s_masks(s, tid, 256);
} };
// One entry's q8_1 row (XB blocks of 36 bytes, 4-byte aligned) into shared memory as entry c: the 8 words of block k
// in planes (HALVES: s_u[(2 c + h) XB + k] = words 4h..4h+3, two 16-byte loads per call, conflict-free over 16
@@ -2740,6 +2809,19 @@ bool g_stage_grid_mmvq = g_stage_grid && [] {
const char* v = std::getenv("STRATA_IQ_STAGE_GRID_MMVQ");
return v != nullptr && v[0] == '1';
}();
// IQ3_XXS's and IQ3_S's codebooks and sign-mask tables staged in shared memory by the grouped expert kernels (the
// single-matrix mmvq does not): bitwise the same either way. OPT-IN: STRATA_IQ_STAGE_TABLES=1. The PR (#1424) made it
// the default on compute capability 6.0 (GP100: no __dp4a, these kernels decode-bound at 70-140 GB/s); on a Tesla P100
// (IQ3_XXS and IQ3_S packs, 5-6 interleaved pairs each) the decode was 0.97-1.03x of the unstaged kernels, noise, so
// it is not on by default. On an RTX 3090 Ti, forced on, the IQ3_S layers took 3-13% longer.
bool stage_tables_on() {
if (!g_stage_grid) return false;
static const bool on = [] {
const char* v = std::getenv("STRATA_IQ_STAGE_TABLES");
return v && v[0] && v[0] != '0';
}();
return on;
}
template<int TY, bool STAGE_GRID = kStageIqGrid<TY>>
void launch_mmvq_multi_nc(dim3 grid, dim3 block, cudaStream_t s, const uint8_t* W, size_t rb, const block_q8_1* X,
@@ -3584,7 +3666,7 @@ void launch_gu(dim3 grid, cudaStream_t s, const unsigned long long* grp_ptr, con
if constexpr (!kSplit<TG>) native_gu_kernel<TG><<<grid, 256, 0, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up);
else if (g_old_kernels) native_gu_kernel<TG><<<grid, 256, 0, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up);
else if constexpr (kStageIqGrid<TG>) {
if (!g_stage_grid) {
if (!g_stage_grid || ((TG == 18 || TG == 21) && !stage_tables_on())) {
if (g_no_sub16_gu) native_gu_multi_kernel<TG, false, false><<<grid, 256, 0, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up);
else native_gu_multi_kernel<TG, false, true><<<grid, 256, 0, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up);
return;
@@ -4689,3 +4771,415 @@ void native_expert_grouped(const NativeExpertLayout& L, const unsigned long long
}
} // namespace strata::kernels
// ---- Volta prompt experts (STRATA_PF_WMMA): a group's experts as one launch of FP16 tensor-core tiles, the weights
// dequantized into shared memory by dq_dispatch (the FP16 path's own formulas), the activations FP16, FP32 sums.
// Replaces MMQ's dp4a products on sm_70, and the FP16 path's dequantize-to-global + one cuBLAS call per expert.
#if !defined(__HIPCC__)
#include <mma.h>
namespace strata::kernels {
namespace {
constexpr int WG_BM = 64, WG_BN = 128, WG_THREADS = 256, WG_XK = 128, WG_MT = 4;
// A block: BN = 128 weight rows of one expert x up to WG_MT * BM = 256 of its token rows (blockIdx.y walks an expert's
// rows in such chunks), so every weight superblock is dequantized ONCE per chunk into shared memory (WK 256: an IQ
// superblock through dq_dispatch; WK 128: two Q2_0 blocks, or four IQ4_NL blocks); the activations stream through a
// BM x 128 tile. 8 warps of 32 x 32 per m-tile (2 x 2 fragments), FP32 accumulators for the chunk's m-tiles in registers.
template<int WK, bool Q20, bool IQNL = false>
__global__ void __launch_bounds__(WG_THREADS) gemm_iq_f16_grouped_kernel(int ty, const uint8_t* __restrict__ W,
size_t expert_bytes, size_t row_bytes, int K,
const __half* __restrict__ X, int ldx,
const int32_t* __restrict__ bounds, int ch_per_e,
float* __restrict__ Y, int ldy) {
#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 700 // the sm_60 pass of a multi-arch build has no nvcuda::wmma (the host never launches these there)
using namespace nvcuda;
constexpr int LDW = WK + 8, LDX = WG_XK + 8;
extern __shared__ __align__(16) unsigned char wg_smem[];
__half* sw = reinterpret_cast<__half*>(wg_smem); // [BN][LDW]
__half* sx = sw + WG_BN * LDW; // [BM][LDX]
const int e = blockIdx.y / ch_per_e, ch = blockIdx.y % ch_per_e;
const int c0 = bounds[e] + ch * WG_MT * WG_BM, r1 = bounds[e + 1];
if (c0 >= r1) return;
const int crow = min(WG_MT * WG_BM, r1 - c0);
const int nmt = (crow + WG_BM - 1) / WG_BM;
const int n0 = blockIdx.x * WG_BN;
const uint8_t* we = W + (size_t) e * expert_bytes;
const int tid = threadIdx.x, warp = tid >> 5, lane = tid & 31;
const int wm = warp >> 2, wn = warp & 3; // rows wm*32, cols wn*32 of an m-tile
wmma::fragment<wmma::accumulator, 16, 16, 16, float> acc[WG_MT][2][2];
#pragma unroll
for (int t = 0; t < WG_MT; ++t)
#pragma unroll
for (int a = 0; a < 2; ++a)
#pragma unroll
for (int b = 0; b < 2; ++b) wmma::fill_fragment(acc[t][a][b], 0.0f);
// the activation tiles in order (k0, m-tile, half): the next one's 4 uint4 per thread are loaded into registers
// while the current one is multiplied (the first before the weights' dequantization)
constexpr int XQ = WG_BM * (WG_XK / 8) / WG_THREADS; // 4
const int nx = WK / WG_XK, per_k = nmt * nx, total = (K / WK) * per_k;
uint4 xr[XQ];
auto load_x = [&](int it) {
const int kb = it / per_k, rem = it % per_k, t = rem / nx, xh = rem % nx;
const int rows = min(WG_BM, crow - t * WG_BM);
#pragma unroll
for (int q = 0; q < XQ; ++q) {
const int i = tid + q * WG_THREADS, r = i / (WG_XK / 8), c = (i % (WG_XK / 8)) * 8;
xr[q] = r < rows ? *reinterpret_cast<const uint4*>(X + (size_t) (c0 + t * WG_BM + r) * ldx + kb * WK + xh * WG_XK + c)
: make_uint4(0, 0, 0, 0);
}
};
load_x(0);
int it = 0;
for (int k0 = 0; k0 < K; k0 += WK) {
if constexpr (IQNL) {
// IQ4_NL down (WK 128 = 4 x block_iq4_nl): one thread per (row, 64-value half) - the four blocks of the
// 128-value window sit in two halves of two blocks, and each thread's values are exactly dq_iq4_nl's
const int r = tid >> 1, half = tid & 1;
const block_iq4_nl* bp = reinterpret_cast<const block_iq4_nl*>(we + (size_t) (n0 + r) * row_bytes) + k0 / 32 + half * 2;
__half* o = sw + r * LDW + half * 64;
#pragma unroll
for (int bl = 0; bl < 2; ++bl) {
const block_iq4_nl* b = bp + bl;
const float d = (float) b->d;
#pragma unroll
for (int p = 0; p < 16; ++p) {
o[bl * 32 + p] = cvt<__half>(d * kvalues_iq4nl[b->qs[p] & 0xf]);
o[bl * 32 + p + 16] = cvt<__half>(d * kvalues_iq4nl[b->qs[p] >> 4]);
}
}
} else if constexpr (!Q20) {
for (int r = warp; r < WG_BN; r += WG_THREADS / 32)
dq_dispatch<__half>(ty, we + (size_t) (n0 + r) * row_bytes, k0 / 256, sw + r * LDW, lane);
} else {
const int r = tid >> 1, blk = tid & 1; // one thread per (row, 64-value block)
const block_q2_0* b = reinterpret_cast<const block_q2_0*>(we + (size_t) (n0 + r) * row_bytes) + k0 / 64 + blk;
const float d = (float) b->d;
uint4 q4;
memcpy(&q4, b->qs, 16);
const uint8_t* qb = reinterpret_cast<const uint8_t*>(&q4);
__half* o = sw + r * LDW + blk * 64;
#pragma unroll
for (int c = 0; c < 16; ++c) {
const int v = qb[c];
*reinterpret_cast<__half2*>(o + 4 * c) = __floats2half2_rn(d * (float) ((v & 3) - 1), d * (float) (((v >> 2) & 3) - 1));
*reinterpret_cast<__half2*>(o + 4 * c + 2) = __floats2half2_rn(d * (float) (((v >> 4) & 3) - 1), d * (float) (((v >> 6) & 3) - 1));
}
}
#pragma unroll
for (int t = 0; t < WG_MT; ++t) {
if (t >= nmt) break;
#pragma unroll 1
for (int xh = 0; xh < WK / WG_XK; ++xh, ++it) {
__syncthreads(); // the previous X tile is consumed (and W is written)
#pragma unroll
for (int q = 0; q < XQ; ++q) {
const int i = tid + q * WG_THREADS, r = i / (WG_XK / 8), c = (i % (WG_XK / 8)) * 8;
*reinterpret_cast<uint4*>(sx + r * LDX + c) = xr[q];
}
__syncthreads();
if (it + 1 < total) load_x(it + 1);
#pragma unroll
for (int kk = 0; kk < WG_XK; kk += 16) {
wmma::fragment<wmma::matrix_a, 16, 16, 16, __half, wmma::row_major> a[2];
wmma::fragment<wmma::matrix_b, 16, 16, 16, __half, wmma::col_major> b[2];
#pragma unroll
for (int f = 0; f < 2; ++f) {
wmma::load_matrix_sync(a[f], sx + (wm * 32 + f * 16) * LDX + kk, LDX);
wmma::load_matrix_sync(b[f], sw + (wn * 32 + f * 16) * LDW + xh * WG_XK + kk, LDW);
}
#pragma unroll
for (int fa = 0; fa < 2; ++fa)
#pragma unroll
for (int fb = 0; fb < 2; ++fb) wmma::mma_sync(acc[t][fa][fb], a[fa], b[fb], acc[t][fa][fb]);
}
}
}
__syncthreads(); // W is consumed before the next superblock
}
float* so = reinterpret_cast<float*>(wg_smem); // [BM][BN + 4] per m-tile
constexpr int LDO = WG_BN + 4;
#pragma unroll
for (int t = 0; t < WG_MT; ++t) {
if (t >= nmt) break;
const int rows = min(WG_BM, crow - t * WG_BM);
#pragma unroll
for (int fa = 0; fa < 2; ++fa)
#pragma unroll
for (int fb = 0; fb < 2; ++fb)
wmma::store_matrix_sync(so + (wm * 32 + fa * 16) * LDO + wn * 32 + fb * 16, acc[t][fa][fb], LDO, wmma::mem_row_major);
__syncthreads();
for (int i = tid; i < rows * (WG_BN / 4); i += WG_THREADS) {
const int r = i / (WG_BN / 4), c = (i % (WG_BN / 4)) * 4;
*reinterpret_cast<float4*>(Y + (size_t) (c0 + t * WG_BM + r) * ldy + n0 + c) = *reinterpret_cast<const float4*>(so + r * LDO + c);
}
__syncthreads();
}
#endif
}
// ---- STRATA_PF_WMMA2=1 (opt-in): IQ2_S gate/up and IQ4_NL down, tiled like a Volta MoE kernel in the
// PR author's own unpublished llama.cpp patches.
// A block: W2_RB = 128 weight rows of one expert x W2_CB = 64 of its sorted rows, K stages of W2_KT = 64. Thread t dequantizes
// row t % 128, 32-value sub-block t / 128 of each K stage from the raw stage in shared memory (one IQ2_S super-block or four IQ4_NL
// blocks per row, read by the whole block as 4-byte words, the next one already in registers). 8 warps = 4 (32 weight rows) x 2
// (32 sorted rows), 2 x 2 wmma 16x16x16 fragments each, FP32 sums.
constexpr int W2_RB = 128, W2_CB = 64, W2_KT = 64, W2_NT = 256, W2_LD = W2_KT + 8;
template <int TY> struct w2_traits;
template <> struct w2_traits<22> { static constexpr int raw_k = 256, raw_b = 82, segw = 21, segw_s = 21, ntab = 1024 + 16; };
template <> struct w2_traits<20> { static constexpr int raw_k = 128, raw_b = 72, segw = 18, segw_s = 19, ntab = 128; };
template <int TY> __host__ __device__ constexpr int w2_nl() { return (W2_RB * w2_traits<TY>::segw + W2_NT - 1) / W2_NT; }
__device__ __forceinline__ uint32_t w2_ld_b2(const uint8_t* p) { // 4 bytes at a 2-byte aligned address
const uint16_t* q = reinterpret_cast<const uint16_t*>(p);
return (uint32_t) q[0] | ((uint32_t) q[1] << 16);
}
__device__ __forceinline__ half2 w2_h2(uint32_t v) { half2 h; memcpy(&h, &v, 4); return h; }
__device__ __forceinline__ uint32_t w2_u32(half2 h) { uint32_t v; memcpy(&v, &h, 4); return v; }
// the raw stage rs of the block's 128 rows: segw words per row from the 4-byte aligned start at or below rs * raw_b
template <int TY>
__device__ __forceinline__ void w2_raw_ld(uint32_t (&R)[w2_nl<TY>()], const uint8_t* __restrict__ xb, size_t row_bytes, int rs, int tid) {
using tr = w2_traits<TY>;
const int off = (rs * tr::raw_b) & ~3;
#pragma unroll
for (int i = 0; i < w2_nl<TY>(); ++i) {
const int w = tid + i * W2_NT;
if ((W2_RB * tr::segw) % W2_NT == 0 || w < W2_RB * tr::segw)
R[i] = *reinterpret_cast<const uint32_t*>(xb + (size_t) (w / tr::segw) * row_bytes + off + 4 * (w % tr::segw));
}
}
template <int TY>
__device__ __forceinline__ void w2_raw_st(const uint32_t (&R)[w2_nl<TY>()], uint32_t* __restrict__ raw, int tid) {
using tr = w2_traits<TY>;
#pragma unroll
for (int i = 0; i < w2_nl<TY>(); ++i) {
const int w = tid + i * W2_NT;
if ((W2_RB * tr::segw) % W2_NT == 0 || w < W2_RB * tr::segw) raw[(w / tr::segw) * tr::segw_s + w % tr::segw] = R[i];
}
}
// sub-block `sb` (0..7) of the IQ2_S super-block at rr -> 32 halves at o, natural order, bit for bit dq_iq2_s's values:
// cvt<__half>(dl * grid[j] * +-1) with dl = d * (0.5 + scale) * 0.25 in FP32 (the sign flips the rounded half, which is the same)
__device__ __forceinline__ float w2_b2f(uint32_t w, int j) { return __int_as_float(0x4B000000 | ((w >> 8 * j) & 0xff)) - 8388608.0f; }
__device__ __forceinline__ void w2_dq_iq2_s(const uint8_t* rr, int sb, __half* o, const uint2* __restrict__ tab) {
const uint2* sgn = tab + 1024;
const uint32_t sc = rr[2 + 64 + 8 + sb], qh = rr[2 + 64 + sb];
const uint32_t qs = w2_ld_b2(rr + 2 + 4 * sb), sg = w2_ld_b2(rr + 2 + 32 + 4 * sb);
const float d = __half2float(__ushort_as_half(*reinterpret_cast<const uint16_t*>(rr)));
const float dl0 = d * (0.5f + (float) (sc & 0xf)) * 0.25f;
const float dl1 = d * (0.5f + (float) (sc >> 4)) * 0.25f;
#pragma unroll
for (int il = 0; il < 4; ++il) {
const float dl = il < 2 ? dl0 : dl1;
const int idx = (int) (((qs >> 8 * il) & 0xff) | ((qh << (8 - 2 * il)) & 0x300));
const uint2 gw = tab[idx];
const uint32_t sbits = (sg >> 8 * il) & 0xff;
const uint2 s0 = sgn[sbits & 15], s1 = sgn[sbits >> 4];
uint4 out;
out.x = w2_u32(__floats2half2_rn(dl * w2_b2f(gw.x, 0), dl * w2_b2f(gw.x, 1))) ^ s0.x;
out.y = w2_u32(__floats2half2_rn(dl * w2_b2f(gw.x, 2), dl * w2_b2f(gw.x, 3))) ^ s0.y;
out.z = w2_u32(__floats2half2_rn(dl * w2_b2f(gw.y, 0), dl * w2_b2f(gw.y, 1))) ^ s1.x;
out.w = w2_u32(__floats2half2_rn(dl * w2_b2f(gw.y, 2), dl * w2_b2f(gw.y, 3))) ^ s1.y;
*reinterpret_cast<uint4*>(o + 8 * il) = out;
}
}
// IQ4_NL block at b -> 32 halves at o, natural order (value j: the low nibble of byte j, value j + 16: its high nibble); the product
// of two exact halves rounded once, as cvt<__half>(d * kvalues_iq4nl[q])
__device__ __forceinline__ void w2_dq_iq4_nl(const uint8_t* b, __half* o, const half2* __restrict__ kv) {
const half2 d2 = __half2half2(__ushort_as_half(*reinterpret_cast<const uint16_t*>(b)));
#pragma unroll
for (int i = 0; i < 4; ++i) {
const uint32_t q = w2_ld_b2(b + 2 + 4 * i);
const half2 t0 = kv[q & 0xff], t1 = kv[(q >> 8) & 0xff], t2 = kv[(q >> 16) & 0xff], t3 = kv[q >> 24];
uint2 lo, hi;
lo.x = w2_u32(__hmul2(__lows2half2(t0, t1), d2));
lo.y = w2_u32(__hmul2(__lows2half2(t2, t3), d2));
hi.x = w2_u32(__hmul2(__highs2half2(t0, t1), d2));
hi.y = w2_u32(__hmul2(__highs2half2(t2, t3), d2));
*reinterpret_cast<uint2*>(o + 4 * i) = lo;
*reinterpret_cast<uint2*>(o + 16 + 4 * i) = hi;
}
}
template <int TY>
__global__ void __launch_bounds__(W2_NT, 2) gemm_iq_f16_w2_kernel(const uint8_t* __restrict__ W, size_t expert_bytes, size_t row_bytes,
int K, const __half* __restrict__ X, int ldx,
const int32_t* __restrict__ bounds, int ch_per_e,
float* __restrict__ Y, int ldy) {
#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 700 // the sm_60 pass of a multi-arch build has no nvcuda::wmma (the host never launches these there)
using namespace nvcuda;
using tr = w2_traits<TY>;
constexpr int NL = w2_nl<TY>(), NSUB = tr::raw_k / W2_KT;
__shared__ __align__(128) __half xs[W2_RB * W2_LD];
__shared__ __align__(128) __half ys[W2_CB * W2_LD];
__shared__ uint2 tab[tr::ntab];
__shared__ uint32_t raw[W2_RB * tr::segw_s];
const int e = blockIdx.y / ch_per_e, ch = blockIdx.y % ch_per_e;
const int c0 = bounds[e] + ch * W2_CB, r1 = bounds[e + 1];
if (c0 >= r1) return;
const int ncol = min(W2_CB, r1 - c0);
const int n0 = blockIdx.x * W2_RB;
const int tid = threadIdx.x, warp = tid >> 5, lane = tid & 31;
const int wr = warp & 3, wc = warp >> 2; // weight rows wr*32, sorted rows wc*32
const uint8_t* xb = W + (size_t) e * expert_bytes + (size_t) n0 * row_bytes;
const int nrs = K / tr::raw_k;
uint32_t R[NL];
w2_raw_ld<TY>(R, xb, row_bytes, 0, tid);
const int yq = tid & 7, yc = tid >> 3; // 16-byte part yq of sorted rows yc and yc + 32
uint4 Yr[2];
auto load_y = [&](int k0) {
#pragma unroll
for (int u = 0; u < 2; ++u) {
const int c = yc + 32 * u;
Yr[u] = c < ncol ? *reinterpret_cast<const uint4*>(X + (size_t) (c0 + c) * ldx + k0 + 8 * yq) : make_uint4(0, 0, 0, 0);
}
};
load_y(0);
if constexpr (TY == 20) {
reinterpret_cast<half2*>(tab)[tid] = __halves2half2(__int2half_rn(kvalues_iq4nl[tid & 15]), __int2half_rn(kvalues_iq4nl[tid >> 4]));
} else {
for (int i = tid; i < 1024; i += W2_NT) tab[i] = reinterpret_cast<const uint2*>(iq2s_grid)[i];
if (tid < 16) // a sign nibble -> masks of its bits 0-1 and 2-3 (bit 2p -> bit 15, bit 2p + 1 -> bit 31)
tab[1024 + tid] = make_uint2(((tid >> 0) & 1u) << 15 | ((tid >> 1) & 1u) << 31, ((tid >> 2) & 1u) << 15 | ((tid >> 3) & 1u) << 31);
}
w2_raw_st<TY>(R, raw, tid);
if (nrs > 1) w2_raw_ld<TY>(R, xb, row_bytes, 1, tid);
__syncthreads();
wmma::fragment<wmma::accumulator, 16, 16, 16, float> acc[2][2];
#pragma unroll
for (int a = 0; a < 2; ++a)
#pragma unroll
for (int b = 0; b < 2; ++b) wmma::fill_fragment(acc[a][b], 0.0f);
const int xr = tid % W2_RB, sub = tid / W2_RB;
__half* xrow = xs + xr * W2_LD + 32 * sub;
const uint8_t* rawrow = reinterpret_cast<const uint8_t*>(raw + xr * tr::segw_s);
for (int rs = 0; rs < nrs; ++rs) {
const uint8_t* rr = rawrow + ((rs * tr::raw_b) & 3);
#pragma unroll
for (int h = 0; h < NSUB; ++h) {
const int k0 = (rs * NSUB + h) * W2_KT;
if constexpr (TY == 20) w2_dq_iq4_nl(rr + 18 * (2 * h + sub), xrow, reinterpret_cast<const half2*>(tab));
else w2_dq_iq2_s(rr, 2 * h + sub, xrow, tab);
#pragma unroll
for (int u = 0; u < 2; ++u) *reinterpret_cast<uint4*>(ys + (yc + 32 * u) * W2_LD + 8 * yq) = Yr[u];
__syncthreads();
if (k0 + W2_KT < K) load_y(k0 + W2_KT);
if (wc * 32 < ncol) { // warp-uniform: sorted rows past the expert's skip their mma
#pragma unroll
for (int kk = 0; kk < W2_KT; kk += 16) {
wmma::fragment<wmma::matrix_a, 16, 16, 16, __half, wmma::row_major> a[2];
wmma::fragment<wmma::matrix_b, 16, 16, 16, __half, wmma::col_major> b[2];
#pragma unroll
for (int f = 0; f < 2; ++f) {
wmma::load_matrix_sync(a[f], ys + (wc * 32 + f * 16) * W2_LD + kk, W2_LD);
wmma::load_matrix_sync(b[f], xs + (wr * 32 + f * 16) * W2_LD + kk, W2_LD);
}
#pragma unroll
for (int fa = 0; fa < 2; ++fa) {
if (wc * 32 + fa * 16 >= ncol) break;
#pragma unroll
for (int fb = 0; fb < 2; ++fb) wmma::mma_sync(acc[fa][fb], a[fa], b[fb], acc[fa][fb]);
}
}
}
if (h == NSUB - 1 && rs + 1 < nrs) { // nobody reads raw between the barrier above and the one below
w2_raw_st<TY>(R, raw, tid);
if (rs + 2 < nrs) w2_raw_ld<TY>(R, xb, row_bytes, rs + 2, tid);
}
__syncthreads();
}
}
// full 16-row tiles straight to Y; the expert's last partial one through the warp's 16 x 16 scratch (ys is free now)
float* scr = reinterpret_cast<float*>(ys) + warp * 256;
#pragma unroll
for (int fa = 0; fa < 2; ++fa) {
const int t0 = wc * 32 + fa * 16;
if (t0 >= ncol) break;
#pragma unroll
for (int fb = 0; fb < 2; ++fb) {
const int nb = n0 + wr * 32 + fb * 16;
if (t0 + 16 <= ncol) {
wmma::store_matrix_sync(Y + (size_t) (c0 + t0) * ldy + nb, acc[fa][fb], ldy, wmma::mem_row_major);
} else {
wmma::store_matrix_sync(scr, acc[fa][fb], 16, wmma::mem_row_major);
__syncwarp();
for (int i = lane; i < 256; i += 32)
if (t0 + i / 16 < ncol) Y[(size_t) (c0 + t0 + i / 16) * ldy + nb + i % 16] = scr[i];
__syncwarp();
}
}
}
#endif
}
bool w2_on() {
static const bool v = [] { const char* e = std::getenv("STRATA_PF_WMMA2"); return e && e[0] == '1'; }();
return v;
}
} // namespace
bool gemm_iq_f16_grouped(int ty, const void* W, size_t expert_bytes, int n_out, int K, const void* X, int ldx,
const int32_t* bounds, int n_experts, int max_rows, float* Y, int ldy, void* stream) {
if (n_out % WG_BN != 0 || n_experts <= 0 || max_rows <= 0 || ldy % 4 != 0) return false;
{ // the tiles are tensor-core kernels: a pre-Volta card has no body for them (the sm_60 pass compiles them empty)
int cur = 0, major = 0;
if (cudaGetDevice(&cur) != cudaSuccess || cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, cur) != cudaSuccess ||
major < 7)
return false;
}
// STRATA_PF_WMMA2=1 (opt-in): IQ2_S gate/up and IQ4_NL down through gemm_iq_f16_w2_kernel (above)
if (w2_on() && n_out % W2_RB == 0 && ldx % 8 == 0 && ldy % 8 == 0 && (uintptr_t) X % 16 == 0 && (uintptr_t) Y % 32 == 0 &&
(uintptr_t) W % 4 == 0 && expert_bytes % 4 == 0 && ((ty == 22 && K % 512 == 0) || (ty == 20 && K % 128 == 0))) {
const size_t rb = iq_row_bytes(ty, K);
const int ch = (max_rows + W2_CB - 1) / W2_CB;
if (rb % 4 == 0 && (long long) n_experts * ch <= 65535) {
const dim3 grid2((unsigned) (n_out / W2_RB), (unsigned) (n_experts * ch));
cudaStream_t s2 = (cudaStream_t) stream;
if (ty == 22)
gemm_iq_f16_w2_kernel<22><<<grid2, W2_NT, 0, s2>>>((const uint8_t*) W, expert_bytes, rb, K, (const __half*) X, ldx, bounds, ch, Y, ldy);
else
gemm_iq_f16_w2_kernel<20><<<grid2, W2_NT, 0, s2>>>((const uint8_t*) W, expert_bytes, rb, K, (const __half*) X, ldx, bounds, ch, Y, ldy);
return cudaGetLastError() == cudaSuccess;
}
}
const bool q20 = ty == 42;
const bool nl = ty == 20 && K % 256 != 0; // IQ4_NL down (K=640): there is no WK=256 path for this K
if (q20 || nl ? K % 128 != 0 : (K % 256 != 0 || !is_iq(ty))) return false;
const size_t row_bytes = iq_row_bytes(ty, K);
const int mt = (max_rows + WG_MT * WG_BM - 1) / (WG_MT * WG_BM); // row chunks per expert
const dim3 grid((unsigned) (n_out / WG_BN), (unsigned) (n_experts * mt));
cudaStream_t s = (cudaStream_t) stream;
auto smem = [](int wk) { return (size_t) WG_BN * (wk + 8) * 2 + (size_t) WG_BM * (WG_XK + 8) * 2; };
// the shared-memory attribute belongs to the current device, so it is set on each card: with one flag for the
// process a layer split's second card launched without it and the prompt stopped ("the WMMA expert tiles could not launch")
static bool attr[64];
int dev = 0;
if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) return false;
if (!attr[dev]) {
cudaFuncSetAttribute(gemm_iq_f16_grouped_kernel<256, false>, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) smem(256));
cudaFuncSetAttribute(gemm_iq_f16_grouped_kernel<128, true>, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) smem(128));
cudaFuncSetAttribute(gemm_iq_f16_grouped_kernel<128, false, true>, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) smem(128));
attr[dev] = true;
}
if (q20)
gemm_iq_f16_grouped_kernel<128, true><<<grid, WG_THREADS, smem(128), s>>>(ty, (const uint8_t*) W, expert_bytes, row_bytes, K,
(const __half*) X, ldx, bounds, mt, Y, ldy);
else if (nl)
gemm_iq_f16_grouped_kernel<128, false, true><<<grid, WG_THREADS, smem(128), s>>>(ty, (const uint8_t*) W, expert_bytes, row_bytes, K,
(const __half*) X, ldx, bounds, mt, Y, ldy);
else
gemm_iq_f16_grouped_kernel<256, false><<<grid, WG_THREADS, smem(256), s>>>(ty, (const uint8_t*) W, expert_bytes, row_bytes, K,
(const __half*) X, ldx, bounds, mt, Y, ldy);
return cudaGetLastError() == cudaSuccess;
}
} // namespace strata::kernels
#else
namespace strata::kernels {
bool gemm_iq_f16_grouped(int, const void*, size_t, int, int, const void*, int, const int32_t*, int, int, float*, int, void*) {
return false;
}
} // namespace strata::kernels
#endif
+83 -1
View File
@@ -73,7 +73,8 @@ __global__ void kv_append_q8_kernel(int8_t* __restrict__ k_q, int8_t* __restrict
}
}
// One thread = 4 consecutive values of one cell and head (as the FP16 gather does with uint2).
// One thread = 4 consecutive values of one cell and head (as the FP16 gather does with uint2). This is the gather
// the ready-made engine runs; the experimental build's 8-wide kernel is below it.
__global__ void kv_gather_q8_kernel(const int8_t* __restrict__ k_q, const int8_t* __restrict__ v_q,
const uint16_t* __restrict__ k_scale, const uint16_t* __restrict__ v_scale,
const int32_t* __restrict__ table, const int32_t* __restrict__ ids,
@@ -106,6 +107,76 @@ __global__ void kv_gather_q8_kernel(const int8_t* __restrict__ k_q, const int8_t
reinterpret_cast<ushort4*>(v_scratch)[dst] = vo;
}
#if defined(STRATA_EXPERIMENTAL_SM60)
// One thread = 8 consecutive values of one cell and head: an 8-byte `uint2` load of codes and a 16-byte `uint4`
// store of the dequantized fp16. The 8 values share one 64-value group, so one scale is loaded per thread and
// the arithmetic stays `(float) code * scale -> f16_from_f32`, i.e. bitwise the same as the previous 4-wide
// version (whose char4 loads became these uint2 loads). `load8_q8` in qsa_decode_attn.cu reads 8 int8 the
// same way; this is the gather's other half. Only in the experimental build (-DSTRATA_EXPERIMENTAL_SM60=ON):
// the ready-made engine keeps exactly the 4-wide kernel above, so its gather is bit for bit the release engine's.
__device__ __forceinline__ uint32_t q8_pair_to_f16x2(const int8_t* c, float s) {
return (uint32_t) f16_from_f32((float) c[0] * s) | ((uint32_t) f16_from_f32((float) c[1] * s) << 16);
}
__global__ void kv_gather_q8_wide_kernel(const int8_t* __restrict__ k_q, const int8_t* __restrict__ v_q,
const uint16_t* __restrict__ k_scale, const uint16_t* __restrict__ v_scale,
const int32_t* __restrict__ table, const int32_t* __restrict__ ids,
const int32_t* __restrict__ step, int kv_heads, int head_dim, int page_size,
uint16_t* __restrict__ k_scratch, uint16_t* __restrict__ v_scratch) {
const long long n_ids = (long long) __ldg(step + kStepWidth);
const int per = head_dim / 8;
const long long total = n_ids * kv_heads * per;
const long long i = blockIdx.x * (long long) blockDim.x + threadIdx.x;
if (i >= total) return;
const long long id = i / (kv_heads * (long long) per);
const int rem = (int) (i % (kv_heads * (long long) per));
const int h = rem / per, q8 = rem - h * per;
const int cell = ids[id];
const long long page = (long long) table[cell / page_size];
const long long row = (page * kv_heads + h) * page_size + (cell % page_size);
const int d = q8 * 8; // 8 divides KV_Q8_GROUP, so all 8 values share the group's scale
const int groups = head_dim / KV_Q8_GROUP;
const float ks = f32_from_f16(k_scale[row * groups + d / KV_Q8_GROUP]);
const float vs = f32_from_f16(v_scale[row * groups + d / KV_Q8_GROUP]);
const uint2 kraw = *reinterpret_cast<const uint2*>(k_q + row * head_dim + d); // one 8-byte load
const uint2 vraw = *reinterpret_cast<const uint2*>(v_q + row * head_dim + d);
const int8_t* kc = reinterpret_cast<const int8_t*>(&kraw);
const int8_t* vc = reinterpret_cast<const int8_t*>(&vraw);
uint4 ko, vo;
ko.x = q8_pair_to_f16x2(kc + 0, ks); ko.y = q8_pair_to_f16x2(kc + 2, ks);
ko.z = q8_pair_to_f16x2(kc + 4, ks); ko.w = q8_pair_to_f16x2(kc + 6, ks);
vo.x = q8_pair_to_f16x2(vc + 0, vs); vo.y = q8_pair_to_f16x2(vc + 2, vs);
vo.z = q8_pair_to_f16x2(vc + 4, vs); vo.w = q8_pair_to_f16x2(vc + 6, vs);
const long long dst = (id * kv_heads + h) * (long long) per + q8;
reinterpret_cast<uint4*>(k_scratch)[dst] = ko;
reinterpret_cast<uint4*>(v_scratch)[dst] = vo;
}
// The current device is below sm_75 (per device: a layer split can mix cards); STRATA_Q8_GATHER_WIDE=0 turns the
// 8-wide gather off (A/B). The wide kernel is bitwise identical, so this only decides speed. Mirrors
// qsa_decode_attn.cu's pre75_attn.
bool pre75_q8_gather() {
static const bool off = [] {
const char* e = std::getenv("STRATA_Q8_GATHER_WIDE");
return e != nullptr && e[0] == '0';
}();
static int cc[64] = {};
int dev = 0;
if (off) return false;
if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) { cudaGetLastError(); return false; }
if (cc[dev] == 0) {
int major = 0, minor = 0;
if (cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev) != cudaSuccess ||
cudaDeviceGetAttribute(&minor, cudaDevAttrComputeCapabilityMinor, dev) != cudaSuccess) {
cudaGetLastError();
return false;
}
cc[dev] = 10 * major + minor;
}
return cc[dev] < 75;
}
#endif // STRATA_EXPERIMENTAL_SM60
} // namespace
void kv_append_q8_step(int8_t* k_q, int8_t* v_q, uint16_t* k_scale, uint16_t* v_scale, const int32_t* page_table,
@@ -136,6 +207,17 @@ void kv_gather_q8_step(const int8_t* k_q, const int8_t* v_q, const uint16_t* k_s
const QsaShapes& s, uint16_t* k_scratch, uint16_t* v_scratch, void* stream) {
validate(s, "kv_gather_q8");
if (max_ids <= 0) return;
#if defined(STRATA_EXPERIMENTAL_SM60)
if (pre75_q8_gather()) {
const long long total = max_ids * s.n_head_kv * (s.head_dim / 8);
const unsigned blocks = (unsigned) ((total + 255) / 256);
kv_gather_q8_wide_kernel<<<blocks, 256, 0, (cudaStream_t) stream>>>(
k_q, v_q, k_scale, v_scale, page_table, ids, step, (int) s.n_head_kv, (int) s.head_dim,
(int) s.page_size, k_scratch, v_scratch);
check("kv_gather_q8 wide launch");
return;
}
#endif
const long long total = max_ids * s.n_head_kv * (s.head_dim / 4);
const unsigned blocks = (unsigned) ((total + 255) / 256);
kv_gather_q8_kernel<<<blocks, 256, 0, (cudaStream_t) stream>>>(
+93 -3
View File
@@ -1920,6 +1920,25 @@ void small_f32(const void* weights, const float* x, void* scratch_q8_1,
small_mmvq<Weight, Qi>(weights, scratch_q8_1, y, n_in, n_out, ncols, stream);
}
// STRATA_Q8_SM60=1 (opt-in, written for Pascal GP100): every Q8_0 dense matrix and the head get the packed planes
// below and run q8sm60::kernel on them (q8_sm60.cuh) instead of the exact kernels.
bool q8_sm60_on() {
#if defined(__HIPCC__)
return false; // a CUDA kernel for one NVIDIA chip: HIP builds never compile it
#else
static const bool on = [] {
const char* v = std::getenv("STRATA_Q8_SM60");
const bool yes = v && v[0] == '1' && v[1] == '\0';
if (yes) std::fprintf(stderr, "strata q8 sm60: Q8_0 decode GEMVs on the Pascal kernel (STRATA_Q8_SM60=1)\n");
return yes;
}();
return on;
#endif
}
#if !defined(__HIPCC__)
#include "q8_sm60.cuh"
#endif
// ============================ STRATA_Q8_PACKED=1: the packed Q8_0 decode layout (opt-in) ============================
//
// A lossless load-time repack of a Q8_0 matrix: the SAME int8 values in a qs plane (row-major, n_in bytes per row)
@@ -2019,8 +2038,30 @@ void q8_packed_launch(const Q8Packed& w, const Q81Block* x, float* y, cudaStream
persist ? grid : w.n_out);
}
bool q8_packed_shape(int n_in, int n_out) { // the shapes native_q8_0_packed_kernel was measured on
return n_in > 0 && n_in % 32 == 0 && n_in / 32 >= 2 * WARPS * WARP / 8 && n_in <= Q8P_PERSIST_MAX_IN &&
n_out >= 2048;
}
bool q8_packed_mmvq(const void* weights, const void* x_q8_1, float* y, int n_in, int n_out, int ncols, void* stream) {
auto& registry = q8_packed_registry();
#if !defined(__HIPCC__)
if (q8_sm60_on() && !registry.empty()) {
const auto found = registry.find(weights);
if (found != registry.end() && found->second.n_in == n_in && found->second.n_out == n_out) {
validate_pointer(x_q8_1);
validate_pointer(y);
validate_stream(stream);
if (q8sm60::launch(found->second.qs, found->second.d, static_cast<const Q81Block*>(x_q8_1), y, n_in,
n_out, ncols, static_cast<cudaStream_t>(stream))) {
launch_check();
return true;
}
// a shape the Pascal kernel declines: the exact packed kernel only where it was measured, else the GGUF layout
if (!q8_packed_shape(n_in, n_out)) return false;
}
}
#endif
if (registry.empty() || (ncols > 1 && !g_multi_exact)) return false; // packed = the EXACT layout only
const auto found = registry.find(weights);
if (found == registry.end() || found->second.n_in != n_in || found->second.n_out != n_out) return false;
@@ -2186,12 +2227,61 @@ bool native_q8_0_packed_enabled() {
const char* v = std::getenv("STRATA_Q8_PACKED");
return v && v[0] == '1' && v[1] == '\0';
}();
return enabled;
return enabled || q8_sm60_on();
}
bool native_q8_0_packed_eligible(int n_in, int n_out) {
return n_in > 0 && n_in % 32 == 0 && n_in / 32 >= 2 * WARPS * WARP / 8 && n_in <= Q8P_PERSIST_MAX_IN &&
n_out >= 2048;
if (q8_sm60_on()) return n_in >= 128 && n_in % 32 == 0 && n_out > 0; // the Pascal kernel takes any of them
return q8_packed_shape(n_in, n_out);
}
namespace {
std::unordered_map<const void*, void*>& q8_sm60_owned() { // packed copies made here (the head), freed by release
static std::unordered_map<const void*, void*> owned;
return owned;
}
} // namespace
bool native_q8_0_sm60_pack(const void* weights, int n_in, int n_out, const char* what) {
#if defined(__HIPCC__)
(void) weights; (void) n_in; (void) n_out; (void) what;
return false;
#else
if (!q8_sm60_on() || !weights || !native_q8_0_packed_eligible(n_in, n_out)) return false;
if (q8_packed_registry().count(weights)) return true;
const std::size_t count = std::size_t(n_in / 32) * std::size_t(n_out);
const std::size_t bytes = count * 34;
void* packed = nullptr;
if (cudaMalloc(&packed, bytes) != cudaSuccess) {
cudaGetLastError();
std::fprintf(stderr, "strata q8 sm60: no VRAM for the packed %s (%.0f MiB); it keeps the GGUF layout\n", what,
double(bytes) / 1048576.0);
return false;
}
auto* qs = static_cast<int8_t*>(packed);
auto* d = reinterpret_cast<half*>(qs + std::size_t(n_in) * n_out);
q8sm60::pack_kernel<<<unsigned((count + 255) / 256), 256>>>(static_cast<const Q80Block*>(weights), qs, d, count);
if (cudaDeviceSynchronize() != cudaSuccess) {
cudaGetLastError();
cudaFree(packed);
std::fprintf(stderr, "strata q8 sm60: packing the %s failed; it keeps the GGUF layout\n", what);
return false;
}
q8_packed_registry()[weights] = Q8Packed{qs, d, n_in, n_out};
q8_sm60_owned()[weights] = packed;
std::fprintf(stderr, "strata q8 sm60: packed %s (%d x %d, %.0f MiB more VRAM)\n", what, n_out, n_in,
double(bytes) / 1048576.0);
return true;
#endif
}
void native_q8_0_sm60_release(const void* weights) {
auto& owned = q8_sm60_owned();
const auto it = owned.find(weights);
if (it == owned.end()) return;
q8_packed_registry().erase(weights);
cudaFree(it->second);
owned.erase(it);
}
void native_q8_0_pack_host(const void* gguf_blocks, void* out, int n_in, int n_out) {
+148
View File
@@ -0,0 +1,148 @@
// src/kernels/cuda/q8_sm60.cuh - a Q8_0 decode GEMV for Pascal GP100 (compute capability 6.0), opt-in with
// STRATA_Q8_SM60=1. Included by native_mmvq.cu, and by a standalone parity/speed check, so both run this code.
//
// Reads the packed planes of STRATA_Q8_PACKED (the SAME int8 values row-major, n_in bytes per row, then one fp16 scale
// per 32 of them) for every Q8_0 dense matrix and the head, whatever their shape. Why the packed kernel above is slow
// on a GP100 die (measured on PH402, 1050 MHz: ~137 GB/s for the dense projections, ~160 for the head, against
// 220-270 for this layout): one workgroup per row, eight bytes per thread per pass and a __syncthreads() per row - a
// 2560-wide row is 80 blocks, so the reduction costs more than the row - and the window's activations read as single
// ints, because a q8_1 block is 36 bytes and its values start at byte 4.
//
// Here:
// * a workgroup first copies the window's activations into shared memory as an int8 plane per column and a float
// scale per 32 (once; the workgroup then loops over rows), so every activation read is a 16-byte shared load;
// * TPR threads own a row (a whole warp for n_in >= 2048, a half or a quarter for narrower rows) and read its
// weights 16 bytes at a time through the read-only cache; the dot of 4 ints is STRATA_DP4A (vmad on sm_60);
// * the sum is a shuffle within those TPR lanes - no shared memory, no barrier per row.
// The per-32 products are added in another order than the exact kernels', so outputs are not bitwise theirs (float
// rounding only; the int8 dots are exact).
#pragma once
namespace q8sm60 {
constexpr int THREADS = 256;
constexpr std::size_t MAX_SMEM = 48 * 1024; // a Pascal workgroup's static + dynamic limit
inline std::size_t smem_bytes(int ncols, int n_in) {
return std::size_t(ncols) * std::size_t(n_in) + std::size_t(ncols) * std::size_t(n_in / 32) * sizeof(float);
}
template<int NCOLS, int TPR>
__launch_bounds__(THREADS)
__global__ void kernel(const int8_t* __restrict__ qs, const half* __restrict__ dpl, const Q81Block* __restrict__ x,
float* __restrict__ y, int n_in, int n_out) {
extern __shared__ int4 q8sm60_smem[];
int8_t* sx = reinterpret_cast<int8_t*>(q8sm60_smem); // [NCOLS][n_in]
float* sd = reinterpret_cast<float*>(sx + std::size_t(NCOLS) * n_in); // [NCOLS][n_in / 32]
const int nb = n_in / 32;
for (int b = int(threadIdx.x); b < NCOLS * nb; b += THREADS) { // column j = b / nb, block b % nb
const Q81Block* xb = x + b;
const int* src = reinterpret_cast<const int*>(xb->qs);
int* dst = reinterpret_cast<int*>(sx + std::size_t(b) * 32);
#pragma unroll
for (int i = 0; i < 8; ++i) dst[i] = src[i];
sd[b] = __low2float(xb->ds);
}
__syncthreads();
constexpr int RPB = THREADS / TPR;
const int lane = int(threadIdx.x) % TPR;
const int rloc = int(threadIdx.x) / TPR;
const int nch = n_in / 16; // 16-byte chunks, two per block
const int groups = (n_out + RPB - 1) / RPB;
for (int g = int(blockIdx.x); g < groups; g += int(gridDim.x)) {
const int row = g * RPB + rloc;
float acc[NCOLS];
#pragma unroll
for (int j = 0; j < NCOLS; ++j) acc[j] = 0.0f;
if (row < n_out) {
const int4* w = reinterpret_cast<const int4*>(qs + std::size_t(row) * n_in);
const half* d = dpl + std::size_t(row) * nb;
for (int c = lane; c < nch; c += TPR) {
const int4 wv = __ldg(w + c);
const float dw = __half2float(d[c >> 1]);
#pragma unroll
for (int j = 0; j < NCOLS; ++j) {
const int4 xv = reinterpret_cast<const int4*>(sx + std::size_t(j) * n_in)[c];
int s = STRATA_DP4A(wv.x, xv.x, 0);
s = STRATA_DP4A(wv.y, xv.y, s);
s = STRATA_DP4A(wv.z, xv.z, s);
s = STRATA_DP4A(wv.w, xv.w, s);
acc[j] += dw * sd[j * nb + (c >> 1)] * float(s);
}
}
}
#pragma unroll
for (int j = 0; j < NCOLS; ++j) { // every lane takes part, row or not
float v = acc[j];
#pragma unroll
for (int o = TPR / 2; o > 0; o >>= 1) v += __shfl_xor_sync(0xffffffffu, v, o, TPR);
if (lane == 0 && row < n_out) y[std::size_t(j) * n_out + row] = v;
}
}
}
// One workgroup per SM would leave too few rows in flight on a 48-SM die; four per SM is what the shapes of
// Qwen3.8-Flash-Next measured best (STRATA_Q8_SM60_BPS overrides it).
inline int blocks_per_sm() {
static const int v = [] {
const char* e = std::getenv("STRATA_Q8_SM60_BPS");
const int n = e ? std::atoi(e) : 0;
return n > 0 ? n : 4;
}();
return v;
}
inline int sm_count() {
int dev = 0, n = 0;
if (cudaGetDevice(&dev) != cudaSuccess || cudaDeviceGetAttribute(&n, cudaDevAttrMultiProcessorCount, dev) != cudaSuccess)
return 48;
return n > 0 ? n : 48;
}
template<int NCOLS, int TPR>
void launch_one(const int8_t* qs, const half* d, const Q81Block* x, float* y, int n_in, int n_out, cudaStream_t s) {
constexpr int RPB = THREADS / TPR;
const int groups = (n_out + RPB - 1) / RPB;
const int grid = (std::min)(groups, sm_count() * blocks_per_sm());
kernel<NCOLS, TPR><<<unsigned(grid), THREADS, smem_bytes(NCOLS, n_in), s>>>(qs, d, x, y, n_in, n_out);
}
template<int NCOLS>
void launch_cols(const int8_t* qs, const half* d, const Q81Block* x, float* y, int n_in, int n_out, cudaStream_t s) {
if (n_in >= 2048) launch_one<NCOLS, 32>(qs, d, x, y, n_in, n_out, s);
else if (n_in >= 1024) launch_one<NCOLS, 16>(qs, d, x, y, n_in, n_out, s);
else launch_one<NCOLS, 8>(qs, d, x, y, n_in, n_out, s);
}
// false: a shape this kernel does not take (the caller runs its usual kernel)
inline bool launch(const int8_t* qs, const half* d, const Q81Block* x, float* y, int n_in, int n_out, int ncols,
cudaStream_t s) {
if (n_in % 32 != 0 || n_in < 128 || ncols < 1 || ncols > 8 || smem_bytes(ncols, n_in) > MAX_SMEM) return false;
switch (ncols) {
case 1: launch_cols<1>(qs, d, x, y, n_in, n_out, s); break;
case 2: launch_cols<2>(qs, d, x, y, n_in, n_out, s); break;
case 3: launch_cols<3>(qs, d, x, y, n_in, n_out, s); break;
case 4: launch_cols<4>(qs, d, x, y, n_in, n_out, s); break;
case 5: launch_cols<5>(qs, d, x, y, n_in, n_out, s); break;
case 6: launch_cols<6>(qs, d, x, y, n_in, n_out, s); break;
case 7: launch_cols<7>(qs, d, x, y, n_in, n_out, s); break;
default: launch_cols<8>(qs, d, x, y, n_in, n_out, s); break;
}
return true;
}
// GGUF Q8_0 blocks (34 bytes, 2-byte aligned) -> the packed planes, on the device (the head's 0.6 GiB stays off the host)
__global__ void pack_kernel(const Q80Block* __restrict__ blocks, int8_t* __restrict__ qs, half* __restrict__ d,
std::size_t count) {
const std::size_t b = std::size_t(blockIdx.x) * blockDim.x + threadIdx.x;
if (b >= count) return;
const Q80Block& src = blocks[b];
const uint16_t* in = reinterpret_cast<const uint16_t*>(src.qs);
uint16_t* out = reinterpret_cast<uint16_t*>(qs + b * 32);
#pragma unroll
for (int i = 0; i < 16; ++i) out[i] = in[i];
d[b] = src.d;
}
} // namespace q8sm60
+67 -31
View File
@@ -1505,7 +1505,7 @@ struct Smem70 {
float alpha[16];
float lsum[16];
float mrow[16];
long long row[CH];
long long row[2][CH]; // double-buffered pool rows: the next chunk's lookups hide under p.v
};
template <int KV_MODE>
@@ -1556,40 +1556,54 @@ __global__ void __launch_bounds__(THREADS) prompt_attn_v70_kernel(const float* _
#pragma unroll
for (int i = 0; i < 8; ++i) acc[rb][nt][i] = 0.0f;
for (int c0 = 0; c0 < n; c0 += CH) {
const int nh = min(CH, n - c0);
if (t < CH) {
long long r = -1;
if (t < nh) {
const int cell = ids[c0 + t];
const long long page = (long long) p.page_table[cell / page_size];
r = (page * n_kv_heads + kvh) * page_size + (cell % page_size);
}
S.row[t] = r;
// the pool rows of a chunk: -1 past the selection and for a page the KV streaming left non-resident (the
// decode kernel masks those, so this kernel does too). Chunk 0's rows fill one buffer here; every later
// chunk's lookups fill the other just before the previous p.v, where their global latency hides.
int rbuf = 0;
if (t < CH) {
long long r = -1;
if (t < min(CH, n)) {
const int cell = ids[t];
const long long page = (long long) p.page_table[cell / page_size];
r = (page * n_kv_heads + kvh) * page_size + (cell % page_size);
}
__syncthreads(); // rows ready; the previous chunk's p.v is done with k, v, s
S.row[0][t] = r;
}
for (int c0 = 0; c0 < n; c0 += CH, rbuf ^= 1) {
const int nh = min(CH, n - c0);
__syncthreads(); // rows ready; the previous chunk's p.v is done with k, v
// gather the chunk's K and V rows (16-byte pieces; K8V4's V as q4_0 blocks dequantized to fp16)
// and their scales
{
constexpr int KPIECES = HD * (int) sizeof(typename Smem<KV_MODE>::KElem) / 16; // per K row
for (int i = t; i < CH * KPIECES; i += THREADS) {
const int c = i / KPIECES, pc = i % KPIECES;
const long long r = S.row[c];
uint4 kx = make_uint4(0, 0, 0, 0);
constexpr int KPT = (CH * KPIECES + THREADS - 1) / THREADS;
static_assert((CH * KPIECES) % THREADS == 0, "the staging pieces divide evenly");
// issue every global load of a thread before any of its stores: they then overlap each other instead
// of paying the HBM latency one at a time
uint4 kx[KPT];
int kc[KPT], kp[KPT];
#pragma unroll
for (int s = 0; s < KPT; ++s) {
const int i = t + s * THREADS;
kc[s] = i / KPIECES; kp[s] = i % KPIECES;
const long long r = S.row[rbuf][kc[s]];
kx[s] = make_uint4(0, 0, 0, 0);
if (r >= 0) {
if constexpr (KV_MODE == 0)
kx = __ldg(reinterpret_cast<const uint4*>(p.k_pool + r * HD) + pc);
kx[s] = __ldg(reinterpret_cast<const uint4*>(p.k_pool + r * HD) + kp[s]);
else // modes 1 and 3: the K side is INT8
kx = __ldg(reinterpret_cast<const uint4*>(p.k_q + r * HD) + pc);
kx[s] = __ldg(reinterpret_cast<const uint4*>(p.k_q + r * HD) + kp[s]);
}
*reinterpret_cast<uint4*>(reinterpret_cast<unsigned char*>(&S.k[c][0]) + pc * 16) = kx;
}
#pragma unroll
for (int s = 0; s < KPT; ++s)
*reinterpret_cast<uint4*>(reinterpret_cast<unsigned char*>(&S.k[kc[s]][0]) + kp[s] * 16) = kx[s];
if constexpr (KV_MODE == 3) { // V: dequantize the row's q4_0 blocks straight into the fp16 V row
constexpr int BLKS = HD / QK4_0;
constexpr int BYTES = BLKS * (int) sizeof(block_q4_0);
for (int i = t; i < CH * BLKS; i += THREADS) {
const int c = i / BLKS, b = i % BLKS;
const long long r = S.row[c];
const long long r = S.row[rbuf][c];
#pragma unroll
for (int j = 0; j < QK4_0; ++j) S.v[c][b * QK4_0 + j] = __half(0);
if (r >= 0) {
@@ -1605,22 +1619,30 @@ __global__ void __launch_bounds__(THREADS) prompt_attn_v70_kernel(const float* _
}
} else {
constexpr int VPIECES = HD * (int) sizeof(typename Smem<KV_MODE>::VElem) / 16; // per V row
for (int i = t; i < CH * VPIECES; i += THREADS) {
const int c = i / VPIECES, pc = i % VPIECES;
const long long r = S.row[c];
uint4 vx = make_uint4(0, 0, 0, 0);
constexpr int VPT = (CH * VPIECES + THREADS - 1) / THREADS;
static_assert((CH * VPIECES) % THREADS == 0, "the staging pieces divide evenly");
uint4 vx[VPT];
int vc[VPT], vp[VPT];
#pragma unroll
for (int s = 0; s < VPT; ++s) {
const int i = t + s * THREADS;
vc[s] = i / VPIECES; vp[s] = i % VPIECES;
const long long r = S.row[rbuf][vc[s]];
vx[s] = make_uint4(0, 0, 0, 0);
if (r >= 0) {
if constexpr (KV_MODE == 1)
vx = __ldg(reinterpret_cast<const uint4*>(p.v_q + r * HD) + pc);
vx[s] = __ldg(reinterpret_cast<const uint4*>(p.v_q + r * HD) + vp[s]);
else
vx = __ldg(reinterpret_cast<const uint4*>(p.v_pool + r * HD) + pc);
vx[s] = __ldg(reinterpret_cast<const uint4*>(p.v_pool + r * HD) + vp[s]);
}
*reinterpret_cast<uint4*>(reinterpret_cast<unsigned char*>(&S.v[c][0]) + pc * 16) = vx;
}
#pragma unroll
for (int s = 0; s < VPT; ++s)
*reinterpret_cast<uint4*>(reinterpret_cast<unsigned char*>(&S.v[vc[s]][0]) + vp[s] * 16) = vx[s];
}
for (int i = t; i < CH * 4; i += THREADS) {
const int c = i / 4, g = i % 4;
const long long r = S.row[c];
const long long r = S.row[rbuf][c];
float a = 0.0f, b = 0.0f;
if (r >= 0) {
if constexpr (KV_MODE == 1) {
@@ -1783,6 +1805,17 @@ __global__ void __launch_bounds__(THREADS) prompt_attn_v70_kernel(const float* _
acc[rb][nt][i] = fmaf(acc[rb][nt][i], a_[(i >> 1) & 1], (tmp[rb][nt][i] + tmpl[rb][nt][i]) * vdown);
}
}
// the next chunk's pool rows, into the other buffer: the two global lookups per cell hide under p.v
if (c0 + CH < n && t < CH) {
long long r = -1;
const int idx = c0 + CH + t;
if (idx < n) {
const int cell = ids[idx];
const long long page = (long long) p.page_table[cell / page_size];
r = (page * n_kv_heads + kvh) * page_size + (cell % page_size);
}
S.row[rbuf ^ 1][t] = r;
}
}
__syncthreads();
#pragma unroll
@@ -2272,10 +2305,13 @@ bool qsa_prompt_attn_batch(const float* q, const QsaAttnPools& pools, const int3
cudaGetLastError();
return false;
}
// STRATA_QSA_WARP=1|attn (an A/B arm): the pre-sm_80 kernels on any card, as RTX 20 runs them
// STRATA_QSA_WARP=1|attn (an A/B arm): the pre-sm_80 kernels on any card that has the Turing MMA (sm_75
// and newer), as RTX 20 runs them. A card below sm_75 has no m16n8k8: its builds hold a __trap() in those
// kernels, so forcing them there killed the engine ("prefill copy_i32: unspecified launch failure" on a
// Tesla P100); such a card ignores the switch and keeps the kernel it runs without it.
const char* w = std::getenv("STRATA_QSA_WARP");
cc[dev] = w && (!std::strcmp(w, "1") || !std::strcmp(w, "attn")) ? 75
: 10 * strata::cc_major_of(major) + strata::cc_minor_of(minor);
const int real_cc = 10 * strata::cc_major_of(major) + strata::cc_minor_of(minor);
cc[dev] = w && (!std::strcmp(w, "1") || !std::strcmp(w, "attn")) && real_cc >= 75 ? 75 : real_cc;
}
if (cc[dev] < 70) return false;
volta = cc[dev] < 75; // sm_70: the m8n8k4 kernel (STRATA_PA_VOLTA); STRATA_QSA_WARP=1 still forces the old one
+190 -104
View File
@@ -22,6 +22,9 @@
// 3. The DEQUANTIZED value is `q * d16`, the fp16 scale, not `q * d32`. The block stores fp16 and that is
// what a reader multiplies by.
#include "strata/kernels/quantize_act.hpp"
#include "strata/kernels/quantize_act_dev.cuh"
#include "strata/kernels/swiglu.cuh"
#include "strata/kernels/bf16_bits.hpp"
#include "strata/kernels/f16_bits.hpp"
#include <cuda_runtime.h>
@@ -48,32 +51,7 @@ __global__ void quantize_q8_0_kernel(const float* __restrict__ x, uint8_t* __res
long long n_blocks) {
const long long b = (long long) blockIdx.x * blockDim.x + threadIdx.x;
if (b >= n_blocks) return;
const float* xb = x + b * QK8_0;
uint8_t* out = blocks + b * 34; // { fp16 d ; int8 qs[32] }
float amax = 0.0f;
for (int i = 0; i < QK8_0; ++i) amax = fmaxf(amax, fabsf(xb[i]));
if (amax == 0.0f) {
// ggml leaves the block zeroed: d = 0 and every q = 0. Writing the fp16 zero explicitly rather than
// skipping keeps the block layout deterministic for the byte comparison.
const uint16_t zb = f16_from_f32(0.0f);
out[0] = (uint8_t) (zb & 0xFF);
out[1] = (uint8_t) (zb >> 8);
for (int i = 0; i < QK8_0; ++i) out[2 + i] = 0;
return;
}
const float d32 = amax / 127.0f;
const uint16_t d16bits = f16_from_f32(d32);
out[0] = (uint8_t) (d16bits & 0xFF);
out[1] = (uint8_t) (d16bits >> 8);
// double division, matching the reference exactly (subtlety 2)
for (int i = 0; i < QK8_0; ++i) {
double q = rint((double) xb[i] / (double) d32);
if (q > 127.0) q = 127.0;
if (q < -128.0) q = -128.0;
out[2 + i] = (uint8_t) (int8_t) q;
}
quantize_q8_0_block(x + b * QK8_0, blocks + b * 34);
}
/// **THE HIT PATH'S QUANTIZER, AND IT EXISTS TO REPRODUCE `act_quant_q8_1` EXACTLY (R4.2h, round 331).**
@@ -102,29 +80,7 @@ __global__ void quantize_q8_0_scaled_kernel(const float* __restrict__ x, uint8_t
float* __restrict__ scales, long long n_blocks) {
const long long b = (long long) blockIdx.x * blockDim.x + threadIdx.x;
if (b >= n_blocks) return;
const float* xb = x + b * QK8_0;
uint8_t* out = blocks + b * 34;
float amax = 0.0f;
for (int i = 0; i < QK8_0; ++i) amax = fmaxf(amax, fabsf(xb[i]));
// VERBATIM from `cpu/expert.cpp:144-145`, including the `amax > 0` guard, so the fp32 value written here
// is bit-identical to the `s` the CPU path used.
const float s = amax > 0.f ? amax / 127.f : 0.f;
const float inv = s > 0.f ? 1.f / s : 0.f;
scales[b] = s;
const uint16_t d16bits = f16_from_f32(s);
out[0] = (uint8_t) (d16bits & 0xFF);
out[1] = (uint8_t) (d16bits >> 8);
for (int i = 0; i < QK8_0; ++i) {
// VERBATIM from `cpu/expert.cpp:159-162`: reciprocal multiply, then `t + copysign(0.5, t)` truncated
// toward zero, which is `lround`'s rule - round half away from zero.
const float t = xb[i] * inv;
const float r = t + (t >= 0.f ? 0.5f : -0.5f);
int v = (int) r;
v = v < -127 ? -127 : (v > 127 ? 127 : v);
out[2 + i] = (uint8_t) (int8_t) v;
}
quantize_q8_0_scaled_block(x + b * QK8_0, blocks + b * 34, scales + b);
}
#else
@@ -180,66 +136,14 @@ __global__ void dequant_q8_0_kernel(const uint8_t* __restrict__ blocks, float* _
constexpr int QK_K = 256;
constexpr int Q8K_BYTES = 292;
/// ggml's `nearest_int` (ggml-quants.c L621), transcribed rather than replaced.
///
/// The magic number is 1.5 * 2^23: adding it forces the mantissa's integer part into the low bits, and the
/// mask/subtract recover it. The reason it is transcribed and not written as `rintf` is that the two differ
/// on exact ties - and that is the whole point of the constant, so a "cleaner" rewrite would silently change
/// which way ties go.
__device__ __forceinline__ int nearest_int_dev(float fval) {
const float val = fval + 12582912.0f;
int i;
memcpy(&i, &val, 4);
return (i & 0x007fffff) - 0x00400000;
}
// `nearest_int_dev` and the per-block quantizers live in `quantize_act_dev.cuh` (shared with the fused
// kernels); the comment that used to justify this copy is there.
__global__ void quantize_q8_K_kernel(const float* __restrict__ x, uint8_t* __restrict__ blocks,
long long n_blocks) {
const long long b = (long long) blockIdx.x * blockDim.x + threadIdx.x;
if (b >= n_blocks) return;
const float* xb = x + b * QK_K;
uint8_t* out = blocks + b * Q8K_BYTES;
float* d = (float*) out;
int8_t* qs = (int8_t*) (out + 4);
int16_t* bsums = (int16_t*) (out + 4 + QK_K);
// `max` is the SIGNED value at the largest magnitude position, and the comparison is STRICTLY greater,
// so a tie keeps the FIRST maximum - which is what `np.argmax` does in the reference transcription too.
float max = 0.0f, amax = 0.0f;
for (int j = 0; j < QK_K; ++j) {
const float ax = fabsf(xb[j]);
if (ax > amax) {
amax = ax;
max = xb[j];
}
}
if (amax == 0.0f) {
// ggml writes d = 0 and zeroes qs, then `continue`s - which LEAVES bsums UNWRITTEN. A zeroed block
// and an untouched one are indistinguishable to the dot product, but not to a byte comparison, so
// this zeroes bsums as well and the parity test's reference does the same. Recorded because it is a
// deliberate divergence from the letter of the source.
*d = 0.0f;
for (int j = 0; j < QK_K; ++j) qs[j] = 0;
for (int j = 0; j < QK_K / 16; ++j) bsums[j] = 0;
return;
}
const float iscale = -127.0f / max; // -127, NOT -128; see the header
for (int j = 0; j < QK_K; ++j) {
// `__fmul_rn`, NOT `iscale * xb[j]`. ggml computes the product, ROUNDS IT TO F32, and then adds
// 12582912.0f inside `nearest_int`. Written as a plain expression, nvcc CONTRACTS the multiply into
// the add as an FMA - which is a more accurate product but not the same one, and it flips the result
// wherever the true product sits just off a .5 boundary. The first version of this kernel differed
// from the reference in 1 element of 524,288 for exactly this reason, and `__fmul_rn` pins the
// rounding step the source actually performs.
const int v = nearest_int_dev(__fmul_rn(iscale, xb[j]));
qs[j] = (int8_t) min(127, v); // MIN only - the source has no lower clamp
}
for (int j = 0; j < QK_K / 16; ++j) {
int sum = 0;
for (int ii = 0; ii < 16; ++ii) sum += qs[j * 16 + ii];
bsums[j] = (int16_t) sum;
}
*d = 1.0f / iscale;
quantize_q8_K_block(x + b * QK_K, blocks + b * Q8K_BYTES);
}
__global__ void dequant_q8_K_kernel(const uint8_t* __restrict__ blocks, float* __restrict__ x,
@@ -254,8 +158,169 @@ __global__ void dequant_q8_K_kernel(const uint8_t* __restrict__ blocks, float* _
for (int i = 0; i < QK_K; ++i) out[i] = (float) qs[i] * d;
}
// ===================== fused silu(gate) * up + quantize =====================
//
// ONE kernel where two ran: `swiglu_kernel` wrote the products and the quantizer read them back. The
// products land in `gate_out` exactly as the standalone kernels stored them and the blocks are the same
// bytes the standalone quantizers produced - the quantizer bodies (`quantize_act_dev.cuh`) run verbatim over
// the shared products. The swilu is PARALLEL (one lane per element): the first version ran 32 exp calls
// serially per thread and measured SLOWER than the two kernels it replaced (M=8: +22.9%).
//
// `SwiluKind` selects the expression because the engine really has three (see `swiglu.cuh`); each is the
// verbatim expression of the standalone kernel that this replaces.
template <int KIND>
__device__ __forceinline__ float swilu_apply(float g, float u) {
if constexpr (KIND == 0) return swilu_legacy(g, u);
else if constexpr (KIND == 1) return swilu_fast(g, u);
else return swilu_native(g, u);
}
// One WARP per 32-element block of pairs: lane j computes pair j (parallel exp), the products stage through
// shared memory, then the quantizer body runs on them exactly as `quantize_q8_0_kernel` did.
template <int KIND, bool SCALED>
__global__ void swilu_quantize_q8_0_kernel(const float* __restrict__ gate, const float* __restrict__ up,
float* __restrict__ gate_out, uint8_t* __restrict__ blocks,
float* __restrict__ scales, long long n_blocks) {
__shared__ float p[4][Q8_0_BLOCK]; // one row per warp (4 warps per block)
const int warps_per_block = (int) (blockDim.x >> 5);
const long long b = (long long) blockIdx.x * warps_per_block + (threadIdx.x >> 5);
const int lane = threadIdx.x & 31;
const int warp = threadIdx.x >> 5;
if (b >= n_blocks) return;
const long long i0 = b * Q8_0_BLOCK;
const float v = swilu_apply<KIND>(gate[i0 + lane], up[i0 + lane]);
gate_out[i0 + lane] = v;
p[warp][lane] = v;
__syncwarp();
if (lane == 0) {
if constexpr (SCALED) quantize_q8_0_scaled_block(p[warp], blocks + b * 34, scales + b);
else quantize_q8_0_block(p[warp], blocks + b * 34);
}
}
// The same for the Q8_K contract (the shared expert's down projection): one warp per 256-element block,
// lane j taking pairs j, j+32, ... so the 256 exp calls spread over the warp.
template <int KIND>
__global__ void swilu_quantize_q8_K_kernel(const float* __restrict__ gate, const float* __restrict__ up,
float* __restrict__ gate_out, uint8_t* __restrict__ blocks,
long long n_blocks) {
__shared__ float p[2][QK_K]; // one row per warp (2 warps per block)
const int warps_per_block = (int) (blockDim.x >> 5);
const long long b = (long long) blockIdx.x * warps_per_block + (threadIdx.x >> 5);
const int lane = threadIdx.x & 31;
const int warp = threadIdx.x >> 5;
if (b >= n_blocks) return;
const long long i0 = b * QK_K;
for (int j = lane; j < QK_K; j += 32) {
const float v = swilu_apply<KIND>(gate[i0 + j], up[i0 + j]);
gate_out[i0 + j] = v;
p[warp][j] = v;
}
__syncwarp();
if (lane == 0) quantize_q8_K_block(p[warp], blocks + b * Q8K_BYTES);
}
template <int KIND>
void swilu_quantize_q8_0_launch(const float* gate, const float* up, float* gate_out, int64_t n, uint8_t* blocks,
float* scales, void* stream) {
const long long nb = n / QK8_0;
const int threads = 128; // 4 warps = 4 blocks of 32 pairs
const unsigned grid = (unsigned) ((nb + 3) / 4);
if (scales != nullptr)
swilu_quantize_q8_0_kernel<KIND, true><<<grid, threads, 0, (cudaStream_t) stream>>>(
gate, up, gate_out, blocks, scales, nb);
else
swilu_quantize_q8_0_kernel<KIND, false><<<grid, threads, 0, (cudaStream_t) stream>>>(
gate, up, gate_out, blocks, nullptr, nb);
const cudaError_t e = cudaGetLastError();
if (e != cudaSuccess) {
std::fprintf(stderr, "swilu_quantize_q8_0 launch: %s\n", cudaGetErrorString(e));
std::exit(1);
}
if (stream == nullptr) cudaDeviceSynchronize();
}
// ===================== every activation image of x in ONE pass =====================
//
// The layer start quantized `x` with two or three kernels (Q8_0, Q8_K, bf16) - three reads of the same
// buffer and three launches, per layer. One kernel here produces whichever images the caller asks for;
// every image's bytes are what its standalone kernel produced (the per-block math is shared, and each block
// reads the same `x` values). Null pointers skip that image.
__global__ void quantize_images_kernel(const float* __restrict__ x, uint8_t* __restrict__ b80,
uint8_t* __restrict__ bK, uint16_t* __restrict__ b16, long long n) {
const long long i = (long long) blockIdx.x * blockDim.x + threadIdx.x;
const long long nb80 = n / Q8_0_BLOCK; // 32-element blocks
if (i < nb80) {
if (b80 != nullptr) quantize_q8_0_block(x + i * Q8_0_BLOCK, b80 + i * Q8_0_BLOCK_BYTES);
if (b16 != nullptr)
for (int j = 0; j < Q8_0_BLOCK; ++j) b16[i * Q8_0_BLOCK + j] = bf16_from_f32(x[i * Q8_0_BLOCK + j]);
}
// q8_K blocks are 256 wide: the thread whose 32-block starts a super-block computes it (256 values in
// one thread, exactly as `quantize_q8_K_kernel` did).
if (bK != nullptr && (i % (Q8_K_BLOCK / Q8_0_BLOCK)) == 0) {
const long long k = i / (Q8_K_BLOCK / Q8_0_BLOCK);
if (i < nb80 && k < n / Q8_K_BLOCK) quantize_q8_K_block(x + k * Q8_K_BLOCK, bK + k * Q8_K_BLOCK_BYTES);
}
}
} // namespace
void swilu_quantize_q8_0(const float* gate, const float* up, float* gate_out, int64_t n, int swilu_kind,
uint8_t* blocks, void* stream) {
if (n <= 0) return;
if (n % QK8_0 != 0) {
std::fprintf(stderr, "swilu_quantize_q8_0: n %lld is not a multiple of %d\n", (long long) n, QK8_0);
std::exit(1);
}
switch (swilu_kind) {
case 0: swilu_quantize_q8_0_launch<0>(gate, up, gate_out, n, blocks, nullptr, stream); break;
case 1: swilu_quantize_q8_0_launch<1>(gate, up, gate_out, n, blocks, nullptr, stream); break;
default: swilu_quantize_q8_0_launch<2>(gate, up, gate_out, n, blocks, nullptr, stream); break;
}
}
void swilu_quantize_q8_0_scaled(const float* gate, const float* up, float* gate_out, int64_t n, int swilu_kind,
uint8_t* blocks, float* scales, void* stream) {
if (n <= 0) return;
if (n % QK8_0 != 0) {
std::fprintf(stderr, "swilu_quantize_q8_0_scaled: n %lld is not a multiple of %d\n", (long long) n, QK8_0);
std::exit(1);
}
if (scales == nullptr) {
std::fprintf(stderr, "swilu_quantize_q8_0_scaled: scales is null\n");
std::exit(1);
}
switch (swilu_kind) {
case 0: swilu_quantize_q8_0_launch<0>(gate, up, gate_out, n, blocks, scales, stream); break;
case 1: swilu_quantize_q8_0_launch<1>(gate, up, gate_out, n, blocks, scales, stream); break;
default: swilu_quantize_q8_0_launch<2>(gate, up, gate_out, n, blocks, scales, stream); break;
}
}
void swilu_quantize_q8_K(const float* gate, const float* up, float* gate_out, int64_t n, int swilu_kind,
uint8_t* blocks, void* stream) {
if (n <= 0) return;
if (n % QK_K != 0) {
std::fprintf(stderr, "swilu_quantize_q8_K: n %lld is not a multiple of %d\n", (long long) n, QK_K);
std::exit(1);
}
const long long nb = n / QK_K;
const int threads = 64; // 2 warps = 2 blocks of 256 pairs
const unsigned grid = (unsigned) ((nb + 1) / 2);
switch (swilu_kind) {
case 0: swilu_quantize_q8_K_kernel<0><<<grid, threads, 0, (cudaStream_t) stream>>>(gate, up, gate_out, blocks, nb); break;
case 1: swilu_quantize_q8_K_kernel<1><<<grid, threads, 0, (cudaStream_t) stream>>>(gate, up, gate_out, blocks, nb); break;
default: swilu_quantize_q8_K_kernel<2><<<grid, threads, 0, (cudaStream_t) stream>>>(gate, up, gate_out, blocks, nb); break;
}
const cudaError_t e = cudaGetLastError();
if (e != cudaSuccess) {
std::fprintf(stderr, "swilu_quantize_q8_K launch: %s\n", cudaGetErrorString(e));
std::exit(1);
}
if (stream == nullptr) cudaDeviceSynchronize();
}
void quantize_q8_0(const float* x, uint8_t* blocks, int64_t n, void* stream) {
if (n <= 0) return;
if (n % QK8_0 != 0) {
@@ -349,4 +414,25 @@ void dequant_q8_K(const uint8_t* blocks, float* x, int64_t n, void* stream) {
if (stream == nullptr) cudaDeviceSynchronize();
}
void quantize_act_images(const float* x, int64_t n, uint8_t* q8_0_blocks, uint8_t* q8_K_blocks,
uint16_t* bf16, void* stream) {
if (n <= 0) return;
if (q8_0_blocks == nullptr && q8_K_blocks == nullptr && bf16 == nullptr) return;
if (n % Q8_0_BLOCK != 0 || (q8_K_blocks != nullptr && n % QK_K != 0)) {
std::fprintf(stderr, "quantize_act_images: n %lld must be a multiple of %d (and %d for Q8_K)\n",
(long long) n, Q8_0_BLOCK, QK_K);
std::exit(1);
}
const long long nb = n / Q8_0_BLOCK;
const int threads = 128;
const unsigned grid = (unsigned) ((nb + threads - 1) / threads);
quantize_images_kernel<<<grid, threads, 0, (cudaStream_t) stream>>>(x, q8_0_blocks, q8_K_blocks, bf16, n);
const cudaError_t e = cudaGetLastError();
if (e != cudaSuccess) {
std::fprintf(stderr, "quantize_act_images launch: %s\n", cudaGetErrorString(e));
std::exit(1);
}
if (stream == nullptr) cudaDeviceSynchronize();
}
} // namespace strata::kernels
+58 -12
View File
@@ -19,6 +19,7 @@
#include "strata/kernels/f16_bits.hpp"
#include "strata/kernels/quantize_act.hpp"
#include "strata/kernels/fuse_decode.hpp"
#include "strata/kernels/verify_kernels.hpp"
#include <cuda_fp16.h>
@@ -161,6 +162,9 @@ __global__ void gu_kernel(const uint8_t* __restrict__ blob_base, const int32_t*
gate_up[base + (size_t) r] = s;
}
// `silu(gate) * up` lives in `strata/kernels/swiglu.cuh` (the fused kernels call it in their epilogues);
// the standalone pass it replaced is gone. The scratch layout is unchanged: `[0, n_pairs)` ends up holding
// the products, `[n_pairs, 2*n_pairs)` the raw up rows.
/// `silu(gate) * up`, in place, over a GATE-MAJOR buffer: `[0, n_pairs)` is every hit's gate and
/// `[n_pairs, 2*n_pairs)` is every hit's up, so hit `h`'s row `r` meets itself at `h*FF + r`.
///
@@ -629,20 +633,30 @@ void moe_hit_grouped_s2(const uint8_t* blob_base, const int32_t* slot_index, con
0, cs);
check("moe_hit_grouped_s2/gu", stream);
}
// 2. silu(gate) * up.
// 2+3. silu(gate) * up, then the intermediate's own contract - ONE kernel where two ran. The products
// land in the gate half exactly as `swiglu_kernel` left them (the parity test compares that scratch),
// and the q8_0 blocks are the same bytes `quantize_q8_0` produced. `swilu_kind` 1 is this file's
// `swiglu_kernel` expression (see `strata/kernels/swiglu.cuh`).
// The down weight is Q2_0, whose `vec_dot_type` is Q8_0 - `ggml_mul_mat`'s rule, not a choice. With
// `x_scales` the intermediate takes the CPU's contract (`quantize_q8_0_scaled`), R4.2h.
{
const long long pairs = n_hits * (long long) FF;
#if defined(STRATA_EXPERIMENTAL_SM60)
if (strata::kernels::fuse_decode()) {
if (x_scales != nullptr)
swilu_quantize_q8_0_scaled(gate_up, gate_up + pairs, gate_up, pairs, 1, h_q8_0, h_scales, stream);
else
swilu_quantize_q8_0(gate_up, gate_up + pairs, gate_up, pairs, 1, h_q8_0, stream);
} else
#endif
{
const unsigned blocks = (unsigned) ((pairs + THREADS - 1) / THREADS);
swiglu_kernel<<<blocks, THREADS, 0, cs>>>(gate_up, pairs);
check("moe_hit_grouped_s2/swiglu", stream);
if (x_scales != nullptr) quantize_q8_0_scaled(gate_up, h_q8_0, h_scales, n_hits * (int64_t) FF, stream);
else quantize_q8_0(gate_up, h_q8_0, n_hits * (int64_t) FF, stream);
}
}
// 3. the intermediate's own contract, which is `ggml_mul_mat`'s rule and NOT a choice: the down weight is
// Q2_0, whose `vec_dot_type` is Q8_0. `gate_up` holds the pairs; the product went into the first half.
// **R4.2h: the CPU quantizes this intermediate into `a2` with fp32 scales too** (`expert.cpp:232`), so
// when the caller supplies `x_scales` the intermediate gets the CPU's contract as well - otherwise the
// down projection would keep the very disagreement the gate/up projection just had removed.
if (x_scales != nullptr) quantize_q8_0_scaled(gate_up, h_q8_0, h_scales, n_hits * (int64_t) FF, stream);
else quantize_q8_0(gate_up, h_q8_0, n_hits * (int64_t) FF, stream);
// 4. down.
{
launch_hit_down(fast, blob_base, slot_index, dst_index, blob_bytes, h_q8_0,
@@ -730,13 +744,25 @@ void moe_hit_grouped_s2_dev(const uint8_t* blob_base, const int32_t* slot_index,
cs);
check("moe_hit_grouped_s2_dev/gu", stream);
}
// silu + intermediate quantization in one kernel (same full-capacity range as the two kernels it replaces,
// sentinel rows included - the parity test compares that scratch).
{
const long long pairs = cap * (long long) FF;
#if defined(STRATA_EXPERIMENTAL_SM60)
if (strata::kernels::fuse_decode()) {
if (x_scales != nullptr)
swilu_quantize_q8_0_scaled(gate_up, gate_up + pairs, gate_up, pairs, 1, h_q8_0, h_scales, stream);
else
swilu_quantize_q8_0(gate_up, gate_up + pairs, gate_up, pairs, 1, h_q8_0, stream);
} else
#endif
{
swiglu_kernel<<<(unsigned) ((pairs + THREADS - 1) / THREADS), THREADS, 0, cs>>>(gate_up, pairs);
check("moe_hit_grouped_s2_dev/swiglu", stream);
if (x_scales != nullptr) quantize_q8_0_scaled(gate_up, h_q8_0, h_scales, cap * (int64_t) FF, stream);
else quantize_q8_0(gate_up, h_q8_0, cap * (int64_t) FF, stream);
}
}
if (x_scales != nullptr) quantize_q8_0_scaled(gate_up, h_q8_0, h_scales, cap * (int64_t) FF, stream);
else quantize_q8_0(gate_up, h_q8_0, cap * (int64_t) FF, stream);
{
launch_hit_down(fast, blob_base, slot_index, dst_index, blob_bytes, h_q8_0,
x_scales != nullptr ? h_scales : nullptr, out, cap, d_count, cs);
@@ -769,11 +795,21 @@ void moe_hit_grouped_s2_multi(const uint8_t* blob_base, const int32_t* slot_inde
}
{
const long long pairs = cap * (long long) FF;
#if defined(STRATA_EXPERIMENTAL_SM60)
if (strata::kernels::fuse_decode()) {
if (x_scales != nullptr)
swilu_quantize_q8_0_scaled(gate_up, gate_up + pairs, gate_up, pairs, 1, h_q8_0, h_scales, stream);
else
swilu_quantize_q8_0(gate_up, gate_up + pairs, gate_up, pairs, 1, h_q8_0, stream);
} else
#endif
{
swiglu_kernel<<<(unsigned) ((pairs + THREADS - 1) / THREADS), THREADS, 0, cs>>>(gate_up, pairs);
check("moe_hit_grouped_s2_multi/swiglu", stream);
if (x_scales != nullptr) quantize_q8_0_scaled(gate_up, h_q8_0, h_scales, cap * (int64_t) FF, stream);
else quantize_q8_0(gate_up, h_q8_0, cap * (int64_t) FF, stream);
}
}
if (x_scales != nullptr) quantize_q8_0_scaled(gate_up, h_q8_0, h_scales, cap * (int64_t) FF, stream);
else quantize_q8_0(gate_up, h_q8_0, cap * (int64_t) FF, stream);
{
launch_hit_down(fast, blob_base, slot_index, dst_index, blob_bytes, h_q8_0,
x_scales != nullptr ? h_scales : nullptr, out, cap, d_count, cs);
@@ -1167,10 +1203,20 @@ void moe_grouped_s2(const unsigned long long* grp_ptr, const int32_t* grp_start,
check("moe_grouped_s2/swiglu_q8", stream);
} else {
const long long pairs = cap_entries * (long long) FF;
#if defined(STRATA_EXPERIMENTAL_SM60)
if (strata::kernels::fuse_decode()) {
if (x_scales != nullptr)
swilu_quantize_q8_0_scaled(gate_up, gate_up + pairs, gate_up, pairs, 1, h_q8_0, h_scales, stream);
else
swilu_quantize_q8_0(gate_up, gate_up + pairs, gate_up, pairs, 1, h_q8_0, stream);
} else
#endif
{
swiglu_kernel<<<(unsigned) ((pairs + THREADS - 1) / THREADS), THREADS, 0, cs>>>(gate_up, pairs);
check("moe_grouped_s2/swiglu", stream);
if (x_scales != nullptr) quantize_q8_0_scaled(gate_up, h_q8_0, h_scales, cap_entries * (int64_t) FF, stream);
else quantize_q8_0(gate_up, h_q8_0, cap_entries * (int64_t) FF, stream);
}
}
{
const dim3 grid((unsigned) (H / D_ROWS), (unsigned) cap_groups);
+136
View File
@@ -0,0 +1,136 @@
// src/kernels/cuda/s_gemv_pair.cu - gate/up dual GEMV + SwiGLU in ONE kernel (llama.cpp's `mul_mat_gated`).
//
// The shared expert ran THREE launches for its two projections and their SwiGLU: the gate GEMV, the up
// GEMV, then a pass over both halves. This kernel computes `out[o] = silu(gate_row_o) * up_row_o` in one
// launch - one read of the activation for both rows - and never materialises `up`.
//
// BITWISE against the unfused pipeline: each row is accumulated by the SAME row function the standalone
// kernel uses (`strata/kernels/s_rowdev.cuh`, shared with nothing else), and the SwiGLU expression is the
// shared one (`strata/kernels/swiglu.cuh`). A float store/load is lossless, so computing the product from
// the register values is what the two-kernel pipeline computed from memory. `fusions_parity` checks this
// bitwise.
//
// The kernel supports every (gate form, up form) pair the S-family dispatch produces: a side is either the
// S2 row (`s2_gemv_q8`, code_bits 2, Q8_0 activations) or an S4/S8 row (`s_gemv_q8_*_split`, Q8_0 or Q8_K
// activations). The per-side kind is a run-time integer picked ONCE per row, outside the accumulation
// loops. Anything else (a non-32 `tpr`, an unknown width) falls back to the unfused sequence.
#include "strata/kernels/s_gemv.hpp"
#include "strata/kernels/s_rowdev.cuh"
#include "strata/kernels/swiglu.cuh"
#include <cuda_runtime.h>
#include <cstdio>
#include <cstdlib>
namespace strata::kernels {
namespace {
// side kinds: 0 = S2 row (Q8_0 act), 1 = split<Q8K>, 2 = split<Q8_0>; widths 4 and 8 fold into `kind`
// below via the template argument chosen at dispatch.
enum { SideS2 = 0, SideQ8K = 1, SideQ80 = 2 };
__device__ __forceinline__ float side_row(int kind, int cb, const uint8_t* x80, const uint8_t* x8k,
const uint8_t* codes, const float* scales, const float* off,
long long n_in, long long o, int lane, int bias, int codebook,
int group_shift, int has_offset, int code_bits,
float* s2partial, int tpr) {
if (kind == SideS2) {
row_s2_q8(x80, codes, scales, n_in, o, lane, tpr, s2partial);
return s2partial[0];
}
const uint8_t* x = kind == SideQ8K ? x8k : x80;
switch (code_bits) {
case 4:
return kind == SideQ8K ? row_s_q8<4, true>(x, codes, scales, off, n_in, o, lane, bias, codebook,
group_shift, has_offset)
: row_s_q8<4, false>(x, codes, scales, off, n_in, o, lane, bias, codebook,
group_shift, has_offset);
default:
return kind == SideQ8K ? row_s_q8<8, true>(x, codes, scales, off, n_in, o, lane, bias, codebook,
group_shift, has_offset)
: row_s_q8<8, false>(x, codes, scales, off, n_in, o, lane, bias, codebook,
group_shift, has_offset);
}
}
struct SideArgs {
int kind, code_bits, bias, codebook, group_shift, has_offset;
const uint8_t *codes, *x80, *x8k;
const float* scales;
const float* off;
};
// ONE WARP PER OUTPUT PAIR: gate row o and up row o, two accumulations, one SwiGLU store.
__global__ void pair_kernel(SideArgs g, SideArgs u, float* __restrict__ out, long long n_in, long long n_out,
int swilu_kind, int tpr) {
__shared__ float s2p[8][32]; // the S2 tree, per warp (8 warps per block)
const int warp_in_block = threadIdx.x >> 5;
const long long o = (long long) blockIdx.x * (blockDim.x >> 5) + warp_in_block;
if (o >= n_out) return;
const int lane = threadIdx.x & 31;
const float ag = side_row(g.kind, g.code_bits, g.x80, g.x8k, g.codes, g.scales, g.off, n_in, o, lane,
g.bias, g.codebook, g.group_shift, g.has_offset, g.code_bits,
s2p[warp_in_block], tpr);
const float au = side_row(u.kind, u.code_bits, u.x80, u.x8k, u.codes, u.scales, u.off, n_in, o, lane,
u.bias, u.codebook, u.group_shift, u.has_offset, u.code_bits,
s2p[warp_in_block], tpr);
if (lane != 0) return;
float v;
if (swilu_kind == 0) v = swilu_legacy(ag, au);
else if (swilu_kind == 1) v = swilu_fast(ag, au);
else v = swilu_native(ag, au);
out[o] = v;
}
bool side_of(const SForm& f, int64_t n_in, const uint8_t* x80, const uint8_t* x8k, const uint8_t* codes,
const float* scales, const float* off, SideArgs* out) {
if (f.code_bits == 2) {
out->kind = SideS2;
} else if (f.code_bits == 4 || f.code_bits == 8) {
out->kind = f.act_kind == 1 ? SideQ8K : SideQ80;
} else {
return false;
}
out->code_bits = f.code_bits;
out->bias = f.code_bias;
out->codebook = (int) f.codebook;
out->group_shift = 0;
while ((1 << out->group_shift) < f.group_elems) ++out->group_shift;
if ((1 << out->group_shift) != f.group_elems) return false;
out->has_offset = f.has_offset ? 1 : 0;
out->codes = codes;
out->scales = scales;
out->off = off;
out->x80 = x80;
out->x8k = x8k;
(void) n_in;
return true;
}
} // namespace
bool s_gemv_pair_silu(const uint8_t* x_q8_0, const uint8_t* x_q8k, const SForm& form_g, const uint8_t* codes_g,
const float* scales_g, const float* off_g, const SForm& form_u, const uint8_t* codes_u,
const float* scales_u, const float* off_u, float* out, int64_t n_in, int64_t n_out,
int threads_per_row, int swilu_kind, void* stream) {
if (n_in <= 0 || n_out <= 0) return false;
// the S2 row's tree is shaped by `threads_per_row`; the standalone kernel takes any tpr, but this
// warp-per-pair form reproduces it only at 32 (the engine's TPR is 32 everywhere).
if (threads_per_row != 32) return false;
SideArgs g, u;
if (!side_of(form_g, n_in, x_q8_0, x_q8k, codes_g, scales_g, off_g, &g)) return false;
if (!side_of(form_u, n_in, x_q8_0, x_q8k, codes_u, scales_u, off_u, &u)) return false;
const int threads = 256; // 8 warps = 8 output pairs
const unsigned grid = (unsigned) ((n_out + 7) / 8);
pair_kernel<<<grid, threads, 0, (cudaStream_t) stream>>>(g, u, out, n_in, n_out, swilu_kind, threads_per_row);
const cudaError_t e = cudaGetLastError();
if (e != cudaSuccess) {
std::fprintf(stderr, "s_gemv_pair_silu launch: %s\n", cudaGetErrorString(e));
std::exit(1);
}
return true;
}
} // namespace strata::kernels
+86
View File
@@ -19,6 +19,7 @@
// BF16 path affects only the scalar gate: it reads the original F32 input and uses pinned CUDA MMVF plus
// an FP32 sigmoid. Native projection overrides independently select CUDA Q8_1 MMVQ and FP32 SwiGLU.
#include "strata/kernels/shared_expert.hpp"
#include "strata/kernels/fuse_decode.hpp"
#include "strata/kernels/bf16_gemv.hpp"
#include "strata/kernels/bf16_bits.hpp"
#include "strata/kernels/f16_bits.hpp"
@@ -330,6 +331,90 @@ void shared_expert(const uint8_t* x_q8_0, const uint8_t* x_q8k, const uint16_t*
const unsigned g_ff = (unsigned) ((n_ff + THREADS - 1) / THREADS);
const unsigned g_embd = (unsigned) ((n_embd + THREADS - 1) / THREADS);
#if defined(STRATA_EXPERIMENTAL_SM60)
if (strata::kernels::fuse_decode()) {
// V100 (experimental sm_70 build): gate and up projections, then silu(gate) * up - ONE kernel when both
// projections are S-family (`s_gemv_pair_silu`: one read of x, SwiGLU in the epilogue, `up` never
// materialised). The pair kernel is bit-exact vs the three-kernel sequence (shared row math, shared
// SwiGLU expression). The ready-made engine's path below is untouched.
bool paired = false;
if (native_gate || native_up)
native_quantize_q8_1(x_f32, native->q8_1, (int) n_embd, 1, stream);
if (!native_gate && !native_up) {
paired = s_gemv_pair_silu(x_q8_0, x_q8k, gate_form, gate_codes, gate_scales, gate_off,
up_form, up_codes, up_scales, up_off, gate, n_embd, n_ff, 32,
native_projection ? 2 : 0, stream);
}
if (paired) {
// `gate` already holds the products
} else {
if (native_gate)
native_mmvq(native->gate_type, native->gate_data, native->q8_1, gate, (int) n_embd, (int) n_ff, 1, stream);
else
gemv(gate_form, gate_codes, gate_scales, gate_off, x_q8_0, x_q8k, gate, n_embd, n_ff);
if (native_up)
native_mmvq(native->up_type, native->up_data, native->q8_1, up, (int) n_embd, (int) n_ff, 1, stream);
else
gemv(up_form, up_codes, up_scales, up_off, x_q8_0, x_q8k, up, n_embd, n_ff);
}
// down: (n_ff) -> (n_embd), and THE INTERMEDIATE IS QUANTIZED TO THE DOWN WEIGHT'S OWN CONTRACT - which is
// what `ggml_mul_mat` does for every matmul in the model. It used to be rounded to fp16 with no
// justification beyond "the kernel takes fp16".
//
// When the pair kernel ran, `gate` already holds the products and only the quantizer is left. Otherwise
// silu(gate) * up AND the quantization are ONE kernel (was: swiglu pass, then quantize); the products
// land in `gate` exactly as `swiglu_kernel` left them and the blocks are the same bytes the standalone
// quantizers produced. The legacy silu is the double-precision `ref/moe.py` form (`swilu_kind` 0).
if (paired) {
if (native_down) {
native_quantize_q8_1(gate, native->q8_1, (int) n_ff, 1, stream);
} else if (down_form.act_kind == 1) {
if (n_ff % 256 != 0) {
std::fprintf(stderr, "shared_expert: the down weight wants Q8_K but n_ff %lld is not a multiple "
"of 256; Q8_K is structurally impossible here\n", (long long) n_ff);
std::exit(1);
}
quantize_q8_K(gate, h_q8k, n_ff, stream);
} else {
quantize_q8_0(gate, h_q8_0, n_ff, stream);
}
} else if (native_projection) {
native_swiglu_kernel<<<g_ff, THREADS, 0, (cudaStream_t) stream>>>(gate, up, gate, (int) n_ff);
if (native_down) {
native_quantize_q8_1(gate, native->q8_1, (int) n_ff, 1, stream);
} else if (down_form.act_kind == 1) {
if (n_ff % 256 != 0) {
std::fprintf(stderr, "shared_expert: the down weight wants Q8_K but n_ff %lld is not a multiple "
"of 256; Q8_K is structurally impossible here\n", (long long) n_ff);
std::exit(1);
}
quantize_q8_K(gate, h_q8k, n_ff, stream);
} else {
quantize_q8_0(gate, h_q8_0, n_ff, stream);
}
} else if (native_down) {
// no fused entry for the Q8_1 contract; the swilu pass and the q8_1 quantizer stay separate
swiglu_kernel<<<g_ff, THREADS, 0, (cudaStream_t) stream>>>(gate, up, gate, (int) n_ff);
native_quantize_q8_1(gate, native->q8_1, (int) n_ff, 1, stream);
} else if (down_form.act_kind == 1) {
if (n_ff % 256 != 0) {
std::fprintf(stderr, "shared_expert: the down weight wants Q8_K but n_ff %lld is not a multiple "
"of 256; Q8_K is structurally impossible here\n", (long long) n_ff);
std::exit(1);
}
swilu_quantize_q8_K(gate, up, gate, n_ff, 0, h_q8k, stream);
} else {
swilu_quantize_q8_0(gate, up, gate, n_ff, 0, h_q8_0, stream);
}
if (native_down) {
native_mmvq(native->down_type, native->down_data, native->q8_1, out, (int) n_ff, (int) n_embd, 1, stream);
} else {
gemv(down_form, down_codes, down_scales, down_off, h_q8_0, h_q8k, out, n_ff, n_embd);
}
} else
#endif
{
// gate and up projections, then silu(gate) * up in place in `gate`
if (native_gate || native_up)
native_quantize_q8_1(x_f32, native->q8_1, (int) n_embd, 1, stream);
@@ -372,6 +457,7 @@ void shared_expert(const uint8_t* x_q8_0, const uint8_t* x_q8k, const uint16_t*
gemv(down_form, down_codes, down_scales, down_off, h_q8_0, h_q8k, out, n_ff, n_embd);
}
}
}
// the per-token scalar gate, then the multiply. Note the gate is computed from `x`, the ORIGINAL hidden
// state, not from anything the expert produced. The historical branch uses BF16-rounded inputs; the
+5 -1
View File
@@ -959,11 +959,15 @@ bool argmax_rows_wanted() {
#if defined(__HIPCC__)
return false;
#else
// sm_80 to sm_89: sample_tokens' greedy pick there is the one-block kernel (sm_90+ has the cluster kernel)
// sm_80 to sm_89, and sm_7x with STRATA_ARGMAX_ROWS_SM70=1: sample_tokens' greedy pick there is the one-block kernel (sm_90+ has the cluster kernel)
static const bool want = [] {
int dev = 0, major = 0;
if (cudaGetDevice(&dev) != cudaSuccess || cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev) != cudaSuccess)
return false;
if (major == 7) { // STRATA_ARGMAX_ROWS_SM70=1: opt-in on Volta (measured on sm_70 only)
const char* e = std::getenv("STRATA_ARGMAX_ROWS_SM70");
return e != nullptr && std::atoi(e) != 0;
}
return major == 8;
}();
return want && multi_block_head_ops();
+281
View File
@@ -0,0 +1,281 @@
// src/kernels/gdn_chunk_parity.cpp - v100/gdn-chunk: the chunked GDN prompt recurrence vs the token recurrence
// and a host reference (GPU, synthetic, no model).
//
// The chunked path (src/prefill/gdn_chunk.cu) computes the SAME recurrence in a different summation order:
// a 64-token chunk becomes one triangular solve and a batch of matmuls instead of 64 sequential rank-1 steps.
// That is FP32-level, NOT bit-exact - the precedent is qsa_prompt_attn.hpp. So this test does not ask for
// equality; it measures the error of both GPU paths against a double-precision transcription of the same
// recurrence (`ref/gdn.py`'s, as re-pinned by gdn_parity) and asserts bounds:
//
// 1. the recurrence vs the host reference: the FP32 floor of the old path,
// 2. the chunked path vs the host reference: the number that matters for the model,
// 3. chunked vs recurrence directly: the observable switch STRATA_GDN_CHUNK flips.
//
// Both GPU paths go through the REAL dispatch (`gdn_recurrence`), A/B'd with the env switch, so the tail
// (< 64 tokens) and the output norm are part of what is compared - the recurrence kernels' raw FP32 output for
// the kernel comparisons (0.1.38's gdn_out_norm_kernel leaves it in place and writes only the FP16 copy), and
// the norm's FP16 output once against the host reference's normalized values.
#include "strata/prefill/gdn_chunk.hpp"
#include "strata/prefill/kernels.hpp"
#include <cuda_runtime.h>
#include <cuda_fp16.h>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <limits>
#include <string>
#include <vector>
namespace {
constexpr int S = 128, HK = 16, HV = 48, C = 10240;
void check(cudaError_t e, const char* what) {
if (e != cudaSuccess) {
std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(e));
std::exit(1);
}
}
// the FP16 store's value back as FP32, for the one normalized-output comparison
float half_to_float(uint16_t u) {
__half h;
std::memcpy(&h, &u, 2);
return __half2float(h);
}
// deterministic LCG - the same inputs on every machine and every run
struct Rng {
uint64_t s;
explicit Rng(uint64_t seed) : s(seed) {}
float uni() {
s = s * 6364136223846793005ULL + 1442695040888963407ULL;
return (float) ((s >> 40) * (1.0 / 16777216.0));
}
};
/// The GDN chunk as a double-precision transcription of the recurrence in strata/kernels/gdn.hpp: the state
/// (S, h_v, S) f32 layout, decay BEFORE the rank-1 update, modulo head pairing. `yraw_out` is the raw output
/// the recurrence kernels leave for gdn_out_norm_kernel; `y_out` is the norm's value, formed exactly as
/// gdn_out_norm_kernel forms it (sqrt(S) in the oc scale, +eps on the SCALED squared norm).
void ref_full(const std::vector<float>& st0, const std::vector<float>& h, const std::vector<float>& gate,
const std::vector<float>& beta, const std::vector<float>& z, const std::vector<float>& gamma,
float eps, int64_t T, std::vector<float>& yraw_out, std::vector<float>& y_out,
std::vector<float>& st_out) {
std::vector<double> st((size_t) S * HV * S);
for (size_t i = 0; i < st.size(); ++i) st[i] = (double) st0[i];
y_out.assign((size_t) T * HV * S, 0.0f);
yraw_out.assign((size_t) T * HV * S, 0.0f);
std::vector<double> o(S);
for (int64_t t = 0; t < T; ++t) {
for (int hh = 0; hh < HV; ++hh) {
const int qh = hh % HK;
const double dec = std::exp((double) gate[(size_t) t * HV + hh]);
const double b = (double) beta[(size_t) t * HV + hh];
for (int j = 0; j < S; ++j) {
double sk = 0.0;
for (int i = 0; i < S; ++i) sk += st[((size_t) i * HV + hh) * S + j] * (double) h[(size_t) t * C + HK * S + qh * S + i];
const double d = ((double) h[(size_t) t * C + 2 * HK * S + hh * S + j] - dec * sk) * b;
for (int i = 0; i < S; ++i) {
double& w = st[((size_t) i * HV + hh) * S + j];
w = dec * w + (double) h[(size_t) t * C + HK * S + qh * S + i] * d;
}
double dot = 0.0;
for (int i = 0; i < S; ++i) dot += st[((size_t) i * HV + hh) * S + j] * (double) h[(size_t) t * C + qh * S + i];
o[j] = dot / std::sqrt((double) S); // the oc scale of gdn_rec_cols_kernel
}
double ss = 0.0;
for (int j = 0; j < S; ++j) ss += o[j] * o[j];
const double rs = 1.0 / std::sqrt(ss / (double) S + (double) eps);
for (int j = 0; j < S; ++j) {
yraw_out[((size_t) t * HV + hh) * S + j] = (float) o[j];
const double sig = 1.0 / (1.0 + std::exp(-(double) z[(size_t) t * HV * S + hh * S + j]));
y_out[((size_t) t * HV + hh) * S + j] = (float) (o[j] * rs * (double) gamma[j] * sig);
}
}
}
st_out.resize(st.size());
for (size_t i = 0; i < st.size(); ++i) st_out[i] = (float) st[i];
}
struct Err {
float abs_ = 0, rel_ = 0;
void see(float a, float b) {
const float d = std::fabs(a - b);
const float m = std::fabs(b);
// a NaN or inf anywhere is a hard error: an unordered comparison would otherwise leave the max at 0
if (!std::isfinite(a) || !std::isfinite(b)) {
abs_ = rel_ = std::numeric_limits<float>::infinity();
return;
}
if (d > abs_) abs_ = d;
const float r = d / (m + 1e-4f);
if (r > rel_) rel_ = r;
}
};
int failures = 0;
void expect(const char* what, const Err& e, float bound_abs, float bound_rel) {
const bool ok = e.rel_ <= bound_rel && e.abs_ <= bound_abs;
std::printf(" %-38s max abs %.3e max rel %.3e (bounds abs %.1e rel %.1e) %s\n", what, e.abs_, e.rel_,
bound_abs, bound_rel, ok ? "ok" : "FAIL");
if (!ok) ++failures;
}
void run_case(int64_t T, uint64_t seed) {
std::printf("T = %lld%s\n", (long long) T, (T % 64) ? " (tail: T % 64 != 0)" : "");
Rng rng(seed);
std::vector<float> h((size_t) T * C), gate((size_t) T * HV), beta((size_t) T * HV), z((size_t) T * HV * S),
gamma(S), st0((size_t) S * HV * S);
for (int64_t t = 0; t < T; ++t) {
for (int qh = 0; qh < HK; ++qh) { // q and k: L2-normalised rows, as gdn_conv leaves them
for (int part = 0; part < 2; ++part) {
double ss = 0;
float row[S];
for (int i = 0; i < S; ++i) {
row[i] = rng.uni() - 0.5f;
ss += (double) row[i] * row[i];
}
const float nrm = (float) (1.0 / std::sqrt(ss + 1e-5));
for (int i = 0; i < S; ++i) h[(size_t) t * C + (part ? HK * S : 0) + qh * S + i] = row[i] * nrm;
}
}
for (int hh = 0; hh < HV; ++hh) {
for (int j = 0; j < S; ++j) // v: O(1) rows
h[(size_t) t * C + 2 * HK * S + hh * S + j] = rng.uni() - 0.5f;
gate[(size_t) t * HV + hh] = -0.02f - 0.3f * rng.uni();
beta[(size_t) t * HV + hh] = 1.0f / (1.0f + std::exp(-(4.0f * rng.uni() - 2.0f)));
for (int j = 0; j < S; ++j) z[((size_t) t * HV + hh) * S + j] = 2.0f * rng.uni() - 1.0f;
}
}
for (int j = 0; j < S; ++j) gamma[j] = 0.5f + 2.0f * rng.uni();
for (size_t i = 0; i < st0.size(); ++i) st0[i] = 0.1f * (rng.uni() - 0.5f);
const float eps = 1e-5f;
std::vector<float> y_ref, yraw_ref, st_ref;
ref_full(st0, h, gate, beta, z, gamma, eps, T, yraw_ref, y_ref, st_ref);
float *d_st = nullptr, *d_h = nullptr, *d_g = nullptr, *d_b = nullptr, *d_z = nullptr, *d_ga = nullptr,
*d_y = nullptr, *d_st0 = nullptr;
uint16_t* d_y16 = nullptr;
check(cudaMalloc(&d_st, st0.size() * 4), "malloc");
check(cudaMalloc(&d_st0, st0.size() * 4), "malloc");
check(cudaMalloc(&d_h, h.size() * 4), "malloc");
check(cudaMalloc(&d_g, gate.size() * 4), "malloc");
check(cudaMalloc(&d_b, beta.size() * 4), "malloc");
check(cudaMalloc(&d_z, z.size() * 4), "malloc");
check(cudaMalloc(&d_ga, gamma.size() * 4), "malloc");
check(cudaMalloc(&d_y, y_ref.size() * 4), "malloc");
check(cudaMalloc(&d_y16, y_ref.size() * 2), "malloc");
check(cudaMemcpy(d_st0, st0.data(), st0.size() * 4, cudaMemcpyHostToDevice), "H2D");
check(cudaMemcpy(d_h, h.data(), h.size() * 4, cudaMemcpyHostToDevice), "H2D");
check(cudaMemcpy(d_g, gate.data(), gate.size() * 4, cudaMemcpyHostToDevice), "H2D");
check(cudaMemcpy(d_b, beta.data(), beta.size() * 4, cudaMemcpyHostToDevice), "H2D");
check(cudaMemcpy(d_z, z.data(), z.size() * 4, cudaMemcpyHostToDevice), "H2D");
check(cudaMemcpy(d_ga, gamma.data(), gamma.size() * 4, cudaMemcpyHostToDevice), "H2D");
std::vector<float> y_gpu(y_ref.size()), st_gpu(st0.size());
std::vector<float> y_rec(y_ref.size()), st_rec(st0.size()), y_warp(y_ref.size()), st_warp(st0.size()),
y_fast(y_ref.size()), st_fast(st0.size()), y_fma(y_ref.size()), st_fma(st0.size());
auto run = [&](const char* chunk, const char* warp, std::vector<float>& y, std::vector<float>& st,
std::vector<float>* y16f = nullptr) {
setenv("STRATA_GDN_CHUNK", chunk, 1);
setenv("STRATA_GDN_REC_WARP", warp, 1);
check(cudaMemcpy(d_st, d_st0, st0.size() * 4, cudaMemcpyDeviceToDevice), "D2D");
strata::prefill::gdn_recurrence(d_st, d_h, d_g, d_b, d_z, d_ga, eps, d_y, d_y16, T, nullptr);
check(cudaDeviceSynchronize(), "sync");
check(cudaMemcpy(y.data(), d_y, y.size() * 4, cudaMemcpyDeviceToHost), "D2H");
check(cudaMemcpy(st.data(), d_st, st.size() * 4, cudaMemcpyDeviceToHost), "D2H");
if (y16f != nullptr) {
std::vector<uint16_t> h16(y.size());
check(cudaMemcpy(h16.data(), d_y16, h16.size() * 2, cudaMemcpyDeviceToHost), "D2H");
y16f->resize(y.size());
for (size_t i = 0; i < y.size(); ++i) (*y16f)[i] = half_to_float(h16[i]);
}
};
std::vector<float> y16_rec;
run("0", "0", y_rec, st_rec, &y16_rec); // the old pipelined recurrence (+ the norm's FP16 output)
run("0", "1", y_warp, st_warp); // the sync-free warp recurrence - must be BIT-EXACT vs the above
run("0", "2", y_fast, st_fast); // the chain-split recurrence (the V100 default)
run("1", "0", y_gpu, st_gpu); // the chunked path's wmma variant
run("2", "0", y_fma, st_fma); // the chunked path's FP32 FMA variant
size_t bits = 0;
for (size_t i = 0; i < y_ref.size(); ++i)
if (std::memcmp(&y_rec[i], &y_warp[i], 4) != 0) ++bits;
for (size_t i = 0; i < st_ref.size(); ++i)
if (std::memcmp(&st_rec[i], &st_warp[i], 4) != 0) ++bits;
std::printf(" %-38s %s\n", "warp recurrence vs pipelined (bits)", bits ? "FAIL" : "bit-exact");
if (bits) ++failures;
Err e_yr, e_y, e_yf, e_ym, e_yc, e_yn, e_sr, e_s, e_sf, e_sm, e_sc;
for (size_t i = 0; i < y_ref.size(); ++i) {
e_yr.see(y_rec[i], yraw_ref[i]);
e_yf.see(y_fast[i], yraw_ref[i]);
e_ym.see(y_fma[i], yraw_ref[i]);
e_y.see(y_gpu[i], yraw_ref[i]);
e_yc.see(y_gpu[i], y_rec[i]);
e_yn.see(y16_rec[i], y_ref[i]);
}
for (size_t i = 0; i < st_ref.size(); ++i) {
e_sr.see(st_rec[i], st_ref[i]);
e_sf.see(st_fast[i], st_ref[i]);
e_sm.see(st_fma[i], st_ref[i]);
e_s.see(st_gpu[i], st_ref[i]);
e_sc.see(st_gpu[i], st_rec[i]);
}
// The bounds are the measured errors of this build on the V100 with ~3x margin (rel uses a 1e-4 floor on
// the reference magnitude). The recurrence is the FP32 floor; the FMA chunked path reorders the sums
// (FP32-level, not bit-exact - qsa_prompt_attn.hpp's precedent); the wmma chunked path additionally
// stages q/k/v and the state through FP16 (the reference's "f32 -> f16 暂存"), which is the error level
// llama.cpp-v100's FlashQLA sm70 path ships with. The y rows compared here are the recurrence kernels'
// raw output (0.1.38's norm keeps its FP32 store out); the last line reads the norm's FP16 copy instead.
expect("recurrence vs host ref (y)", e_yr, 5e-6f, 1e-2f);
expect("chain-split recurrence (y)", e_yf, 1e-5f, 2e-2f);
expect("chunked FMA vs host ref (y)", e_ym, 1e-5f, 2e-2f);
expect("chunked wmma vs host ref (y)", e_y, 6e-3f, 5e1f);
expect("chunked wmma vs recurrence (y)", e_yc, 6e-3f, 5e1f);
expect("output norm (FP16) vs host ref (y)", e_yn, 8e-3f, 5e-2f);
expect("recurrence vs host ref (state)", e_sr, 1e-7f, 5e-4f);
expect("chain-split recurrence (state)", e_sf, 5e-7f, 2e-3f);
expect("chunked FMA vs host ref (state)", e_sm, 5e-7f, 2e-3f);
expect("chunked wmma vs host ref (state)", e_s, 3e-4f, 2e0f);
expect("chunked wmma vs recurrence (state)", e_sc, 3e-4f, 2e0f);
cudaFree(d_st); cudaFree(d_st0); cudaFree(d_h); cudaFree(d_g); cudaFree(d_b); cudaFree(d_z);
cudaFree(d_ga); cudaFree(d_y); cudaFree(d_y16);
}
} // namespace
int main(int argc, char** argv) {
bool selftest = false;
for (int i = 1; i < argc; ++i) {
if (std::strcmp(argv[i], "--selftest") == 0) selftest = true;
else { std::fprintf(stderr, "usage: gdn_chunk_parity [--selftest]\n"); return 2; }
}
{
// the kkt stage needs 2*64*129 floats (66 KB) of dynamic shared memory: a card whose opt-in limit is lower
// (Pascal: 48 KB) cannot launch it, and the engine dispatch never selects the chunked path there
int dev = 0, smem = 0;
cudaGetDevice(&dev);
cudaDeviceGetAttribute(&smem, cudaDevAttrMaxSharedMemoryPerBlockOptin, dev);
if (smem < 2 * 64 * 129 * 4) {
std::printf("gdn_chunk_parity: the card's shared-memory opt-in (%d B) is below the kkt stage's need, skipped\n", smem);
return 77;
}
}
if (!strata::prefill::gdn_chunk_available())
std::printf("note: not a V100 (cc 7.0) - the parity still runs; the engine dispatch keeps the recurrence\n");
run_case(64, 1);
run_case(128, 2);
run_case(200, 3); // tail: T % 64 = 8
run_case(320, 4);
std::printf("\ngdn_chunk: %d failures\n", failures);
if (selftest && failures == 0) std::printf("gdn_chunk_parity OK\n");
return failures ? 1 : 0;
}
+10 -2
View File
@@ -333,8 +333,16 @@ int main() {
// AMD: the tensor-core prompt path is CUDA-only, so it refuses every pool and the old kernel runs
std::printf("[5/5] qsa_prompt_attn mode 3: PASS (refused on HIP - the old kernel runs)\n");
#else
std::printf("[5/5] qsa_prompt_attn mode 3: FAIL (refused the hybrid pools)\n");
g_fail = 1;
// a card below compute capability 7.0 (Pascal) never had the tensor-core prompt kernels: the old kernel runs
int dev5 = 0, major5 = 0;
cudaGetDevice(&dev5);
cudaDeviceGetAttribute(&major5, cudaDevAttrComputeCapabilityMajor, dev5);
if (major5 > 0 && major5 < 7) {
std::printf("[5/5] qsa_prompt_attn mode 3: PASS (refused below sm_70 - the old kernel runs)\n");
} else {
std::printf("[5/5] qsa_prompt_attn mode 3: FAIL (refused the hybrid pools)\n");
g_fail = 1;
}
#endif
} else {
k::fwht256_inplace_cuda(d_at4, QH, nullptr);
+50 -1
View File
@@ -29,7 +29,56 @@ void ck(cudaError_t e, const char* w) {
template <typename T> T* dalloc(size_t n) { T* p = nullptr; ck(cudaMalloc(&p, n * sizeof(T) + 64), "malloc"); ck(cudaMemset(p, 0, n * sizeof(T) + 64), "memset"); return p; }
} // namespace
int main() {
// A decode-shaped microbench: a 32k pool, the 2,051-cell selection the QSA decoder gathers per layer, random
// cells (so the reads miss L2). Reports the gather's effective traffic per call and GB/s. Not part of the test.
int bench() {
k::QsaShapes s = k::qsa_real_shapes();
const int H = (int) s.n_head_kv, D = (int) s.head_dim, P = (int) s.page_size, G = D / k::KV_Q8_GROUP;
const int ctx = 32768, pages = ctx / P;
const long long rows = (long long) pages * H * P;
const int max_ids = (int) k::qsa_selection_width(ctx, s);
std::mt19937 rng(7);
std::vector<int8_t> kq((size_t) rows * D), vq((size_t) rows * D);
std::vector<uint16_t> ks((size_t) rows * G), vs((size_t) rows * G);
for (auto& x : kq) x = (int8_t) (rng() & 0xFF);
for (auto& x : vq) x = (int8_t) (rng() & 0xFF);
for (auto& x : ks) x = (uint16_t) (0x3000 | (rng() & 0x3FF));
for (auto& x : vs) x = (uint16_t) (0x3000 | (rng() & 0x3FF));
std::vector<int32_t> table(pages);
for (int i = 0; i < pages; ++i) table[i] = i;
std::shuffle(table.begin(), table.end(), rng);
std::vector<int32_t> ids(max_ids);
for (auto& x : ids) x = (int32_t) (rng() % ctx);
int8_t* d_kq = dalloc<int8_t>(kq.size()); ck(cudaMemcpy(d_kq, kq.data(), kq.size(), cudaMemcpyHostToDevice), "up");
int8_t* d_vq = dalloc<int8_t>(vq.size()); ck(cudaMemcpy(d_vq, vq.data(), vq.size(), cudaMemcpyHostToDevice), "up");
uint16_t* d_ks = dalloc<uint16_t>(ks.size()); ck(cudaMemcpy(d_ks, ks.data(), ks.size() * 2, cudaMemcpyHostToDevice), "up");
uint16_t* d_vs = dalloc<uint16_t>(vs.size()); ck(cudaMemcpy(d_vs, vs.data(), vs.size() * 2, cudaMemcpyHostToDevice), "up");
int32_t* d_table = dalloc<int32_t>(pages); ck(cudaMemcpy(d_table, table.data(), pages * 4, cudaMemcpyHostToDevice), "up");
int32_t* d_ids = dalloc<int32_t>(max_ids); ck(cudaMemcpy(d_ids, ids.data(), max_ids * 4, cudaMemcpyHostToDevice), "up");
int32_t* d_step = dalloc<int32_t>(k::kStepCount);
int32_t hstep[k::kStepCount] = {0, 0, 0, max_ids};
ck(cudaMemcpy(d_step, hstep, sizeof hstep, cudaMemcpyHostToDevice), "up");
uint16_t* k8 = dalloc<uint16_t>((size_t) max_ids * H * D);
uint16_t* v8 = dalloc<uint16_t>((size_t) max_ids * H * D);
for (int i = 0; i < 5; ++i) k::kv_gather_q8_step(d_kq, d_vq, d_ks, d_vs, d_table, d_ids, d_step, max_ids, s, k8, v8, nullptr);
ck(cudaDeviceSynchronize(), "warmup");
const int reps = 200;
cudaEvent_t e0, e1; cudaEventCreate(&e0); cudaEventCreate(&e1);
cudaEventRecord(e0);
for (int r = 0; r < reps; ++r) k::kv_gather_q8_step(d_kq, d_vq, d_ks, d_vs, d_table, d_ids, d_step, max_ids, s, k8, v8, nullptr);
cudaEventRecord(e1); ck(cudaEventSynchronize(e1), "time");
float ms = 0; cudaEventElapsedTime(&ms, e0, e1);
const double bytes = (double) max_ids * H * D * 2 // K + V codes
+ (double) max_ids * H * G * 2 * 2 // K + V scales
+ (double) max_ids * H * D * 2 * 2; // K + V fp16 scratch write
const double us = ms * 1000.0 / reps;
std::printf("kv_gather_q8 bench: %d ids, %.1f us/call, %.1f GB/s (%.2f MB moved)\n", max_ids, us,
bytes / (us * 1e-6) / 1e9, bytes / 1e6);
return 0;
}
int main(int argc, char** argv) {
for (int i = 1; i < argc; ++i) if (!std::strcmp(argv[i], "--bench")) return bench();
k::QsaShapes s = k::qsa_real_shapes();
s.page_size = 64; // several pages in a small pool
const int H = (int) s.n_head_kv, D = (int) s.head_dim, P = (int) s.page_size, G = D / k::KV_Q8_GROUP;
+160
View File
@@ -0,0 +1,160 @@
// src/kernels/pf_wmma_parity.cpp - gemm_iq_f16_grouped (the Volta prompt experts, STRATA_PF_WMMA) against a double
// reference over the same FP16 weights (iq_dequant_f16, the FP16 path's dequantization) and FP16 activations.
//
// build/pf_wmma_parity (needs a CUDA GPU with FP16 tensor cores: sm_70+; synthetic blobs, no model)
//
// Every gate/up format the prompt path gives it (IQ2_XXS, IQ2_S, IQ1_M, and this pack's IQ4_NL / IQ3_S / IQ4_XS: 1280
// rows of 2560) and the down products (Q2_0, and IQ4_NL: 2560 rows of 640); a group of experts with 0, 1, 63, 64, 65,
// 200 and 300 rows (one past the 256-row chunk); the rows placed past a nonzero first bound. The sums are FP32 on
// tensor cores in another order than the reference, so the check is a tolerance: max |got - ref| <= 2e-3 * (max |ref|
// of the matrix) + 1e-6.
#include "strata/kernels/iq_kernels.hpp"
#include <cuda_fp16.h>
#include <cuda_runtime.h>
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <random>
#include <vector>
namespace k = strata::kernels;
namespace {
void ck(cudaError_t e, const char* what) {
if (e != cudaSuccess) {
std::fprintf(stderr, "CUDA error in %s: %s\n", what, cudaGetErrorString(e));
std::exit(2);
}
}
const char* name_of(int t) {
switch (t) {
case 16: return "IQ2_XXS";
case 17: return "IQ2_XS";
case 18: return "IQ3_XXS";
case 20: return "IQ4_NL";
case 21: return "IQ3_S";
case 22: return "IQ2_S";
case 23: return "IQ4_XS";
case 29: return "IQ1_M";
case 42: return "Q2_0";
case 12: return "Q4_K";
case 13: return "Q5_K";
case 14: return "Q6_K";
case 7: return "Q5_1";
case 8: return "Q8_0";
default: return "?";
}
}
int block_values(int t) { return t == 20 || t == 7 || t == 8 ? 32 : t == 42 ? 64 : 256; }
// `rows` rows of `n` values of format t: random bytes, then a finite fp16 scale in every block
std::vector<uint8_t> random_rows(int t, int64_t rows, int64_t n, std::mt19937& rng) {
const size_t rb = k::iq_row_bytes(t, n), bs = k::iq_row_bytes(t, block_values(t));
std::vector<uint8_t> w((size_t) rows * rb);
std::uniform_int_distribution<int> byte(0, 255), ex(2, 8), man(0, 1023), sgn(0, 1);
for (auto& b : w) b = (uint8_t) byte(rng);
for (size_t o = 0; o < w.size(); o += bs) {
if (t == 29) {
// IQ1_M: the fp16 scale is the top nibbles of its four scale words (bytes 48..55), the sign and the
// exponent's top bits in the last: 0x1 / 0x2 there (0x9 / 0xA negative) keeps it in 2^-11 .. 2^-3
const uint8_t nib = (uint8_t) ((sgn(rng) ? 0x8 : 0x0) | (1 + (byte(rng) & 1)));
w[o + 55] = (uint8_t) ((w[o + 55] & 0x0F) | (nib << 4));
} else { // the other formats start their block with the fp16 scale: 2^-13 .. 2^-6
// (Q4_K / Q5_K: 2^-14 .. 2^-11, their 6-bit sub-scales multiply it by up to 63)
const int e = (t == 12 || t == 13) ? 1 + ex(rng) % 4 : ex(rng);
const uint16_t h = (uint16_t) ((sgn(rng) ? 0x8000 : 0) | (e << 10) | man(rng));
std::memcpy(&w[o], &h, 2);
if (t == 12 || t == 13 || t == 7) { // Q4_K / Q5_K: dmin, Q5_1: m - the second fp16, as small
const int em = (t == 7) ? ex(rng) : 1 + ex(rng) % 4;
const uint16_t m = (uint16_t) ((sgn(rng) ? 0x8000 : 0) | (em << 10) | man(rng));
std::memcpy(&w[o + 2], &m, 2);
}
}
}
return w;
}
int run(int ty, int n_out, int K, std::mt19937& rng) {
const std::vector<int> rows = {0, 1, 63, 64, 65, 200, 300};
const int E = (int) rows.size(), base = 5;
std::vector<int32_t> bounds(E + 1);
bounds[0] = base;
for (int e = 0; e < E; ++e) bounds[e + 1] = bounds[e] + rows[e];
const int total = bounds[E];
const size_t eb = k::iq_row_bytes(ty, K) * (size_t) n_out;
std::vector<uint8_t> w;
for (int e = 0; e < E; ++e) { auto r = random_rows(ty, n_out, K, rng); w.insert(w.end(), r.begin(), r.end()); }
std::normal_distribution<float> nd(0.f, 1.f);
std::vector<__half> x((size_t) total * K);
for (auto& v : x) v = __float2half(nd(rng));
uint8_t* dw; __half* dx; int32_t* db; float* dy; uint16_t* dq;
ck(cudaMalloc(&dw, w.size() + 4096), "w");
ck(cudaMemcpy(dw, w.data(), w.size(), cudaMemcpyHostToDevice), "w");
ck(cudaMalloc(&dx, x.size() * 2), "x");
ck(cudaMemcpy(dx, x.data(), x.size() * 2, cudaMemcpyHostToDevice), "x");
ck(cudaMalloc(&db, bounds.size() * 4), "b");
ck(cudaMemcpy(db, bounds.data(), bounds.size() * 4, cudaMemcpyHostToDevice), "b");
ck(cudaMalloc(&dy, (size_t) total * n_out * 4), "y");
ck(cudaMemset(dy, 0xff, (size_t) total * n_out * 4), "y");
ck(cudaMalloc(&dq, (size_t) E * n_out * K * 2), "dq");
const int maxr = *std::max_element(rows.begin(), rows.end());
if (!k::gemm_iq_f16_grouped(ty, dw, eb, n_out, K, dx, K, db, E, maxr, dy, n_out, nullptr)) {
std::printf("%-8s %5d x %4d: not launched\n", name_of(ty), n_out, K);
return 1;
}
for (int e = 0; e < E; ++e) k::iq_dequant_f16(ty, dw + e * eb, (int64_t) n_out * K, dq + (size_t) e * n_out * K, nullptr);
ck(cudaDeviceSynchronize(), "run");
std::vector<float> y((size_t) total * n_out);
std::vector<uint16_t> q((size_t) E * n_out * K);
ck(cudaMemcpy(y.data(), dy, y.size() * 4, cudaMemcpyDeviceToHost), "y");
ck(cudaMemcpy(q.data(), dq, q.size() * 2, cudaMemcpyDeviceToHost), "dq");
double worst = 0, scale = 0;
for (int e = 0; e < E; ++e)
for (int r = bounds[e]; r < bounds[e + 1]; ++r)
for (int n = 0; n < n_out; ++n) {
double s = 0;
const uint16_t* wr = &q[((size_t) e * n_out + n) * K];
for (int kk = 0; kk < K; ++kk) {
__half h; std::memcpy(&h, &wr[kk], 2);
s += (double) __half2float(h) * (double) __half2float(x[(size_t) r * K + kk]);
}
scale = std::max(scale, std::fabs(s));
worst = std::max(worst, std::fabs(s - (double) y[(size_t) r * n_out + n]));
}
const bool ok = worst <= 2e-3 * scale + 1e-6;
std::printf("%-8s %5d x %4d, %d rows in %d experts: max |err| %.3g of max |ref| %.3g %s\n", name_of(ty), n_out, K,
total - base, E, worst, scale, ok ? "ok" : "FAIL");
cudaFree(dw); cudaFree(dx); cudaFree(db); cudaFree(dy); cudaFree(dq);
return ok ? 0 : 1;
}
} // namespace
int main() {
// every sm_70+ card in one process, in turn: a layer split launches the tiles on its second card after the first
int n_dev = 0, ran = 0, fails = 0;
cudaGetDeviceCount(&n_dev);
for (int dev = 0; dev < n_dev; ++dev) {
int major = 0;
cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev);
if (major < 7) continue;
cudaSetDevice(dev);
std::printf("device %d\n", dev);
++ran;
std::mt19937 rng(70);
for (int ty : {16, 22, 29}) fails += run(ty, 1280, 2560, rng);
fails += run(42, 2560, 640, rng);
for (int ty : {20, 21, 23}) fails += run(ty, 1280, 2560, rng); // this pack's gate/up formats, generic WK=256 path
fails += run(20, 2560, 640, rng); // the IQ4_NL down, the new WK=128 lane
}
if (!ran) { std::printf("pf_wmma_parity: needs sm_70+, skipped\n"); return 77; }
std::printf("pf_wmma_parity: %d failures on %d devices\n", fails, ran);
return fails ? 1 : 0;
}
+636
View File
@@ -0,0 +1,636 @@
// src/prefill/gdn_chunk.cu - see include/strata/prefill/gdn_chunk.hpp for the math and the contract.
//
// Three kernels, the same three stages as llama.cpp-v100's gdn-chunk-sm70 (cumsum / kkt / fwd), hand-written
// plain CUDA - FP32 throughout, no FP16 staging and no tensor cores yet (the TileLang m8n8k4 output of the
// reference is a later, speed-only step). What the chunking buys is the shape of the serial chain: T tokens
// become T/64 chunk steps, each step a batch of dense matmuls over 64 tokens instead of one token's rank-1
// update behind two __syncthreads.
//
// Per CTA: one (v head, 32-column slice) of the state, all chunks in order (the state slice lives in
// registers - the chunk-serial scan of the reference's fwd kernel). The per-chunk 64x64 matrices A and P are
// computed once per (chunk, head) by the kkt kernel and read by the four column slices.
#include "strata/prefill/gdn_chunk.hpp"
#include <cuda_runtime.h>
#if !defined(__HIPCC__)
#include <cuda_fp16.h>
#include <mma.h>
#endif
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <mutex>
namespace strata::prefill {
namespace {
constexpr int S = 128, HK = 16, HV = 48, C = 10240; // the geometry of src/prefill/kernels.cu
constexpr int CH = 64; // tokens per chunk (the reference's chunk)
constexpr int NS = 32; // value columns per fwd CTA
constexpr int NSE = S / NS; // 4 slices per head
constexpr int SEG = 32; // chunks per pipeline segment (sizes the workspace)
// the wmma kernel's dynamic shared memory: Ks/Qs f16, W16 f16, Ug f32 (Gram scratch / U out), As/Ps f16,
// dlt f32 and its f16 image - 84 KB, past the 48 KB default (opt-in), under the 96 KB Volta ceiling
constexpr int WMMA_SMEM = (2 * CH * S + S * NS) * (int) sizeof(__half) + S * NS * (int) sizeof(float) +
2 * CH * CH * (int) sizeof(__half) + CH * NS * (int) sizeof(float) +
CH * NS * (int) sizeof(__half);
void check(const char* what) {
const cudaError_t e = cudaGetLastError();
if (e != cudaSuccess) {
std::fprintf(stderr, "gdn_chunk %s: %s\n", what, cudaGetErrorString(e));
std::exit(1);
}
}
// g_cumsum[lt * HV + h] = inclusive cumsum of gate over the segment's tokens (lt = segment-local token).
// One block of 64 per (chunk, head): a Kogge-Stone scan of 64 values, two tokens' worth of nothing.
__global__ void __launch_bounds__(CH) gdn_chunk_cumsum_kernel(float* __restrict__ gcum,
const float* __restrict__ gate, int ntok) {
const int h = blockIdx.y;
const int lt = blockIdx.x * CH + threadIdx.x;
__shared__ float sh[CH];
sh[threadIdx.x] = lt < ntok ? gate[(size_t) lt * HV + h] : 0.0f;
__syncthreads();
#pragma unroll
for (int off = 1; off < CH; off <<= 1) {
const float add = threadIdx.x >= off ? sh[threadIdx.x - off] : 0.0f;
__syncthreads();
sh[threadIdx.x] += add;
__syncthreads();
}
if (lt < ntok) gcum[(size_t) lt * HV + h] = sh[threadIdx.x];
}
// Per (chunk, head): the decayed Gram matrices the fwd kernel's solve and output sum read,
// A[t][s] = beta_t exp(c_t - c_s) (k_t . k_s) for s < t (the (I + strict_lower) solve matrix)
// P[t][s] = exp(c_t - c_s) (q_t . k_s) for s <= t (the output sum)
// in f32 (CH x CH per chunk-head; the upper triangle of A and P is never written and never read). Every
// decay factor is a decay from a LATER token back to an EARLIER one - <= 1 for a real GDN gate - so nothing
// here can overflow, and delta stays O(beta v) in the fwd solve (gdn_chunk.hpp derives the form).
__global__ void __launch_bounds__(128) gdn_chunk_kkt_kernel(float* __restrict__ A, float* __restrict__ P,
const float* __restrict__ h,
const float* __restrict__ beta,
const float* __restrict__ gcum, int nchunks) {
// 2 * CH * SP f32: the k and q tiles (opt-in, > 48 KB). SP pads the row so the dot loop's row-strided
// reads do not all land in one shared bank (S = 128 floats is a whole number of bank rows).
constexpr int SP = S + 1;
extern __shared__ float sh[];
float* ks = sh;
float* qs = sh + CH * SP;
const int hh = blockIdx.y, ch = blockIdx.x, qh = hh % HK;
const int64_t base = (size_t) ch * CH;
const float* kh = h + base * C + (size_t) HK * S + (size_t) qh * S;
const float* qh_ = h + base * C + (size_t) qh * S;
for (int i = threadIdx.x; i < CH * S; i += blockDim.x) {
const int t = i / S, j = i % S;
ks[t * SP + j] = kh[(size_t) t * C + j];
qs[t * SP + j] = qh_[(size_t) t * C + j];
}
__syncthreads();
float* Ap = A + ((size_t) ch * HV + hh) * CH * CH;
float* Pp = P + ((size_t) ch * HV + hh) * CH * CH;
for (int p = threadIdx.x; p < CH * CH; p += blockDim.x) {
const int t = p / CH, s = p % CH;
if (s > t) continue;
const float dec = expf(gcum[(base + t) * HV + hh] - gcum[(base + s) * HV + hh]);
float pq = 0.0f, pq1 = 0.0f;
#pragma unroll 4
for (int i = 0; i < S; i += 2) {
pq = fmaf(qs[t * SP + i], ks[s * SP + i], pq);
pq1 = fmaf(qs[t * SP + i + 1], ks[s * SP + i + 1], pq1);
}
Pp[t * CH + s] = (pq + pq1) * dec;
if (s < t) {
float pk = 0.0f, pk1 = 0.0f;
#pragma unroll 4
for (int i = 0; i < S; i += 2) {
pk = fmaf(ks[t * SP + i], ks[s * SP + i], pk);
pk1 = fmaf(ks[t * SP + i + 1], ks[s * SP + i + 1], pk1);
}
Ap[t * CH + s] = (pk + pk1) * dec * beta[(base + t) * HV + hh];
}
}
}
// The chunk-serial scan: one CTA per (v head, 32-column slice), state in registers, all chunks in order.
// Per token: the two row-block reductions (k_t.W_in, q_t.W_in) give u_t and qW_t; the w==0 lane of each
// column solves its delta and writes o. The A/P tiles are staged to shared memory at the top of each chunk:
// the solve and output sums are serial FMA chains, and a global load inside the chain (L2, ~200 cycles)
// throttles the whole CTA to it. One __syncthreads per token (the shared dlt row plus the partials), one
// after the token loop (the last dlt row before the state update).
__global__ void __launch_bounds__(128) gdn_chunk_fwd_kernel(float* __restrict__ state, float* __restrict__ oc,
const float* __restrict__ h,
const float* __restrict__ beta,
const float* __restrict__ gcum,
const float* __restrict__ A,
const float* __restrict__ P, int nchunks) {
const int hh = blockIdx.y, sl = blockIdx.x, j0 = sl * NS, qh = hh % HK;
const int w = threadIdx.x >> 5, c = threadIdx.x & 31, col = j0 + c;
// red is double-buffered by token parity: the w==0 lane reads token t's partials while the other warps
// may already be staging token t+1's into the other slot (one barrier per token, no reader/writer race)
__shared__ float red[2][2][4][NS], dlt[CH][NS], As[CH][CH], Ps[CH][CH], ex[CH][2];
float W[NS];
#pragma unroll
for (int r = 0; r < NS; ++r)
W[r] = state[((size_t) (w * NS + r) * HV + hh) * S + col];
const float rsqrt_S = rsqrtf((float) S);
for (int ch = 0; ch < nchunks; ++ch) {
const int64_t base = (size_t) ch * CH;
const float sg = gcum[(base + CH - 1) * HV + hh]; // sigma: the chunk's total log-decay
const float* Ap = A + ((size_t) ch * HV + hh) * CH * CH;
const float* Pp = P + ((size_t) ch * HV + hh) * CH * CH;
// stage the two 64x64 tiles and the per-token decay factors (exp(c_t), exp(sigma - c_t))
for (int i = threadIdx.x; i < CH * CH; i += blockDim.x) {
As[i / CH][i % CH] = Ap[i];
Ps[i / CH][i % CH] = Pp[i];
}
if (threadIdx.x < CH) {
const float gc = gcum[(base + threadIdx.x) * HV + hh];
ex[threadIdx.x][0] = expf(gc);
ex[threadIdx.x][1] = expf(sg - gc);
}
__syncthreads();
const float sg_exp = ex[CH - 1][0]; // exp(sigma)
for (int t = 0; t < CH; ++t) {
const float* kt = h + (base + t) * C + (size_t) HK * S + (size_t) qh * S + w * NS;
const float* qt = h + (base + t) * C + (size_t) qh * S + w * NS;
float up = 0.0f, up1 = 0.0f, qp = 0.0f, qp1 = 0.0f;
#pragma unroll
for (int r = 0; r < NS; r += 2) {
const float w0 = W[r], w1 = W[r + 1];
up = fmaf(kt[r], w0, up);
up1 = fmaf(kt[r + 1], w1, up1);
qp = fmaf(qt[r], w0, qp);
qp1 = fmaf(qt[r + 1], w1, qp1);
}
red[t & 1][0][w][c] = up + up1;
red[t & 1][1][w][c] = qp + qp1;
__syncthreads();
if (w == 0) {
const float u_t = red[t & 1][0][0][c] + red[t & 1][0][1][c] + red[t & 1][0][2][c] + red[t & 1][0][3][c];
const float qW_t =
red[t & 1][1][0][c] + red[t & 1][1][1][c] + red[t & 1][1][2][c] + red[t & 1][1][3][c];
const float b = beta[(base + t) * HV + hh];
const float v_t = h[(base + t) * C + (size_t) 2 * HK * S + (size_t) hh * S + col];
// delta_t = beta_t (v_t - exp(c_t) u_t) - sum_{s<t} A[t][s] delta_s
float d = b * (v_t - ex[t][0] * u_t), d1 = 0.0f;
#pragma unroll 1
for (int s = 0; s < t; s += 2) {
d = fmaf(-As[t][s], dlt[s][c], d);
if (s + 1 < t) d1 = fmaf(-As[t][s + 1], dlt[s + 1][c], d1);
}
d += d1;
dlt[t][c] = d;
float o = ex[t][0] * qW_t + Ps[t][t] * d, o1 = 0.0f;
#pragma unroll 1
for (int s = 0; s < t; s += 2) {
o = fmaf(Ps[t][s], dlt[s][c], o);
if (s + 1 < t) o1 = fmaf(Ps[t][s + 1], dlt[s + 1][c], o1);
}
oc[((base + t) * HV + hh) * S + col] = (o + o1) * rsqrt_S;
}
}
__syncthreads(); // the last dlt row is visible for the update
// W_out = exp(sigma) W_in + sum_s k_s exp(sigma - c_s) delta_s^T (the decay folded into the delta)
#pragma unroll
for (int r = 0; r < NS; ++r) W[r] *= sg_exp;
for (int s = 0; s < CH; ++s) {
const float* kt = h + (base + s) * C + (size_t) HK * S + (size_t) qh * S + w * NS;
const float ds = dlt[s][c] * ex[s][1];
#pragma unroll
for (int r = 0; r < NS; ++r) W[r] = fmaf(kt[r], ds, W[r]);
}
}
#pragma unroll
for (int r = 0; r < NS; ++r) state[((size_t) (w * NS + r) * HV + hh) * S + col] = W[r];
}
// ---------------------------------------------------------------- wmma (m16n16k16) variant
//
// The FMA scan above is correct but latency-bound: per token it streams k_t and q_t from global into
// dependent FMA chains, and V100 FMA throughput cannot pay for that at this granularity (measured on the
// V100: ~2x slower than the recurrence it was meant to beat). This variant runs the same math the way
// llama.cpp-v100's gdn-chunk-sm70 does it - q/k/v and the state staged through FP16, the matmuls on the
// FP16 tensor cores with FP32 accumulate, the triangular solve still FMA - and folds the kkt stage's Gram
// matrices into the same CTA (recomputed per column slice, which the tensor cores make cheap).
//
// Per chunk: stage k/q, -> f16; Gram K K^T and Q K^T -> A and P (decay + beta baked); the GEMM
// U = [K; Q] W gives u_t and qW_t for every token at once; the solve and output sums are the FMA scan's;
// W += K^T (delta * decay) on the tensor cores with W itself as the f32 accumulator fragments - the state
// never leaves the registers across chunks. W's f16 image exists only as the U GEMM's operand.
//
// Precision: the FP16 staging is the reference's "f32 -> f16 暂存" (10-bit mantissa on the operands);
// accumulations, the solve and the state are f32. FP32-level, not bit-exact - see gdn_chunk_parity.
#if !defined(__HIPCC__)
__global__ void __launch_bounds__(128) gdn_chunk_wmma_kernel(float* __restrict__ state, float* __restrict__ oc,
const float* __restrict__ h,
const float* __restrict__ beta,
const float* __restrict__ gcum, int nchunks) {
#if !defined(__CUDA_ARCH__) || __CUDA_ARCH__ >= 700 // named in every device pass of a multi-arch build; only sm_70+ has wmma
namespace wmma = ::nvcuda::wmma;
// smem (84.5 KB, opt-in): Ks/Qs the chunk's k and q rows f16; W16 the state slice f16 (U's operand);
// Ug[128][32] f32 aliasing the 64x64 Gram scratch and then U = [K;Q] W; As/Ps f16; dlt f32 + f16.
extern __shared__ __align__(1024) unsigned char smem[];
__half* Ks = (__half*) smem; // [CH][S]
__half* Qs = Ks + CH * S; // [CH][S]
__half* W16 = Qs + CH * S; // [S][NS]
float* Ug = (float*) (W16 + S * NS); // [S][NS] f32 (Gram scratch / U out)
__half* As = (__half*) (Ug + S * NS); // [CH][CH]
__half* Ps = As + CH * CH; // [CH][CH]
float* dlt = (float*) (Ps + CH * CH); // [CH][NS]
__half* dlt16 = (__half*) (dlt + CH * NS); // [CH][NS]
const int hh = blockIdx.y, sl = blockIdx.x, j0 = sl * NS, qh = hh % HK;
const int w = threadIdx.x >> 5, c = threadIdx.x & 31, col = j0 + c;
// the state slice in through smem (load_matrix_sync of an accumulator tile is a shared-memory op on
// sm_70): Ug first as the f32 staging, then W's f32 image in the fragments and its f16 image in W16
for (int i = threadIdx.x; i < S * NS; i += blockDim.x) {
const int r = i / NS, j = i % NS;
Ug[i] = state[(size_t) r * HV * S + (size_t) hh * S + j0 + j];
W16[i] = __float2half_rn(Ug[i]);
}
__syncthreads();
// W as f32 accumulator fragments: warp w owns rows w*32..w*32+31 of the 128x32 slice, 2x2 tiles
wmma::fragment<wmma::accumulator, 16, 16, 16, float> wF[2][2];
#pragma unroll
for (int mi = 0; mi < 2; ++mi)
#pragma unroll
for (int nj = 0; nj < 2; ++nj)
wmma::load_matrix_sync(wF[mi][nj], Ug + (size_t) (w * 32 + 16 * mi) * NS + 16 * nj, NS,
wmma::mem_row_major);
const float rsqrt_S = rsqrtf((float) S);
for (int ch = 0; ch < nchunks; ++ch) {
const int64_t base = (size_t) ch * CH;
const float sg = gcum[(base + CH - 1) * HV + hh]; // sigma: the chunk's total log-decay
// stage the chunk's k and q rows through f16 - float4 loads, four in flight per thread: a scalar
// load loop here is a serial global-latency chain per thread (measured: it WAS the kernel's floor)
for (int i4 = threadIdx.x; i4 < CH * S / 4; i4 += blockDim.x) {
const int t = (i4 * 4) / S, j4 = (i4 * 4) % S;
const float4 k4 = *reinterpret_cast<const float4*>(h + (base + t) * C + (size_t) HK * S + (size_t) qh * S + j4);
const float4 q4 = *reinterpret_cast<const float4*>(h + (base + t) * C + (size_t) qh * S + j4);
Ks[t * S + j4 + 0] = __float2half_rn(k4.x);
Ks[t * S + j4 + 1] = __float2half_rn(k4.y);
Ks[t * S + j4 + 2] = __float2half_rn(k4.z);
Ks[t * S + j4 + 3] = __float2half_rn(k4.w);
Qs[t * S + j4 + 0] = __float2half_rn(q4.x);
Qs[t * S + j4 + 1] = __float2half_rn(q4.y);
Qs[t * S + j4 + 2] = __float2half_rn(q4.z);
Qs[t * S + j4 + 3] = __float2half_rn(q4.w);
}
// the state slice as f16: the fragments to Ug, then to W16
#pragma unroll
for (int mi = 0; mi < 2; ++mi)
#pragma unroll
for (int nj = 0; nj < 2; ++nj)
wmma::store_matrix_sync(Ug + (size_t) (w * 32 + 16 * mi) * NS + 16 * nj, wF[mi][nj], NS,
wmma::mem_row_major);
__syncthreads();
for (int i = threadIdx.x; i < S * NS; i += blockDim.x) W16[i] = __float2half_rn(Ug[i]);
__syncthreads(); // W16 done before Ug becomes the Gram scratch
// Gram: Ug = K K^T, then As[t][s] = beta_t exp(c_t-c_s) Ug[t][s]; Ug = Q K^T, then Ps (no beta)
{
wmma::fragment<wmma::matrix_a, 16, 16, 16, __half, wmma::row_major> aF;
wmma::fragment<wmma::matrix_b, 16, 16, 16, __half, wmma::col_major> bF;
wmma::fragment<wmma::accumulator, 16, 16, 16, float> gF[4];
for (int pass = 0; pass < 2; ++pass) {
#pragma unroll
for (int nj = 0; nj < 4; ++nj) wmma::fill_fragment(gF[nj], 0.0f);
for (int kk = 0; kk < S / 16; ++kk) {
wmma::load_matrix_sync(aF, (pass ? Qs : Ks) + (size_t) (w * 16) * S + kk * 16, S);
for (int nj = 0; nj < 4; ++nj) {
wmma::load_matrix_sync(bF, Ks + kk * 16 + (size_t) (16 * nj) * S, S);
wmma::mma_sync(gF[nj], aF, bF, gF[nj]);
}
}
for (int nj = 0; nj < 4; ++nj)
wmma::store_matrix_sync(Ug + (size_t) (w * 16) * CH + 16 * nj, gF[nj], CH, wmma::mem_row_major);
__syncthreads();
// fold decay (and beta) into the f16 tiles
for (int p = threadIdx.x; p < CH * CH; p += blockDim.x) {
const int t = p / CH, s = p % CH;
const float dec = expf(gcum[(base + t) * HV + hh] - gcum[(base + s) * HV + hh]);
if (pass) // Ps: s <= t live, the upper triangle zeroed - the o GEMM reads the whole tile
Ps[t * CH + s] = s <= t ? __float2half_rn(Ug[t * CH + s] * dec) : __float2half_rn(0.0f);
else if (s < t) // As: strict lower only, the solve reads exactly that
As[t * CH + s] = __float2half_rn(Ug[t * CH + s] * dec * beta[(base + t) * HV + hh]);
}
__syncthreads();
}
}
// U = [K; Q] W16 : rows 0..63 are u_t = k_t.W_in, rows 64..127 are qW_t = q_t.W_in. The 128 output
// rows split as 32 per warp: warps 0-1 the K half, warps 2-3 the Q half.
{
wmma::fragment<wmma::matrix_a, 16, 16, 16, __half, wmma::row_major> aF;
wmma::fragment<wmma::matrix_b, 16, 16, 16, __half, wmma::row_major> bF[2];
wmma::fragment<wmma::accumulator, 16, 16, 16, float> uF[2][2];
const __half* src = w < 2 ? Ks : Qs;
const int row0 = (w & 1) * 32;
#pragma unroll
for (int mi = 0; mi < 2; ++mi)
#pragma unroll
for (int nj = 0; nj < 2; ++nj) wmma::fill_fragment(uF[mi][nj], 0.0f);
for (int kk = 0; kk < S / 16; ++kk) {
for (int nj = 0; nj < 2; ++nj)
wmma::load_matrix_sync(bF[nj], W16 + kk * 16 * NS + 16 * nj, NS);
#pragma unroll
for (int mi = 0; mi < 2; ++mi) {
wmma::load_matrix_sync(aF, src + (size_t) (row0 + 16 * mi) * S + kk * 16, S);
for (int nj = 0; nj < 2; ++nj) wmma::mma_sync(uF[mi][nj], aF, bF[nj], uF[mi][nj]);
}
}
#pragma unroll
for (int mi = 0; mi < 2; ++mi)
#pragma unroll
for (int nj = 0; nj < 2; ++nj)
wmma::store_matrix_sync(Ug + (size_t) (w * 32 + 16 * mi) * NS + 16 * nj, uF[mi][nj], NS,
wmma::mem_row_major);
__syncthreads();
}
// the solve - 8 independent accumulator chains so the smem loads of one group hide behind the FMAs
// of the last (the 2-chain was smem-latency-bound and WAS half the kernel's runtime)
for (int t = 0; t < CH; ++t) {
if (w == 0) {
const float gc = gcum[(base + t) * HV + hh];
const float ex0 = expf(gc);
const float b = beta[(base + t) * HV + hh];
const float v_t = h[(base + t) * C + (size_t) 2 * HK * S + (size_t) hh * S + col];
float d[8];
d[0] = b * (v_t - ex0 * Ug[t * NS + c]);
#pragma unroll
for (int q = 1; q < 8; ++q) d[q] = 0.0f;
int s0 = 0;
#pragma unroll 1
for (; s0 + 8 <= t; s0 += 8) {
#pragma unroll
for (int q = 0; q < 8; ++q)
d[q] = fmaf(-__half2float(As[t * CH + s0 + q]), dlt[(s0 + q) * NS + c], d[q]);
}
#pragma unroll 1
for (; s0 < t; ++s0) d[0] = fmaf(-__half2float(As[t * CH + s0]), dlt[s0 * NS + c], d[0]);
dlt[t * NS + c] = (d[0] + d[1] + d[2] + d[3]) + (d[4] + d[5] + d[6] + d[7]);
}
}
__syncthreads(); // the deltas are complete
for (int i = threadIdx.x; i < CH * NS; i += blockDim.x) dlt16[i] = __float2half_rn(dlt[i]);
__syncthreads();
// o_intra = Ps delta on the tensor cores (the o FMA sum was the other latency chain), staged into the
// As tile (dead since the solve); 64 output rows split 16 per warp
{
wmma::fragment<wmma::matrix_a, 16, 16, 16, __half, wmma::row_major> aF;
wmma::fragment<wmma::matrix_b, 16, 16, 16, __half, wmma::row_major> bF[2];
wmma::fragment<wmma::accumulator, 16, 16, 16, float> oF[2];
for (int nj = 0; nj < 2; ++nj) wmma::fill_fragment(oF[nj], 0.0f);
for (int kk = 0; kk < CH / 16; ++kk) {
for (int nj = 0; nj < 2; ++nj)
wmma::load_matrix_sync(bF[nj], dlt16 + (size_t) (kk * 16) * NS + 16 * nj, NS);
wmma::load_matrix_sync(aF, Ps + (size_t) (w * 16) * CH + kk * 16, CH);
for (int nj = 0; nj < 2; ++nj) wmma::mma_sync(oF[nj], aF, bF[nj], oF[nj]);
}
for (int nj = 0; nj < 2; ++nj)
wmma::store_matrix_sync(Ug + S * NS + (size_t) (w * 16) * NS + 16 * nj, oF[nj], NS,
wmma::mem_row_major); // (the As tile's byte range)
}
__syncthreads();
for (int i = threadIdx.x; i < CH * NS; i += blockDim.x) {
const int t = i / NS;
oc[((base + t) * HV + hh) * S + j0 + (i % NS)] =
(Ug[S * NS + i] + expf(gcum[(base + t) * HV + hh]) * Ug[(64 + t) * NS + (i % NS)]) * rsqrt_S;
}
__syncthreads();
// dlt16 = f16(delta_s * exp(sigma - c_s)) - the decay folded in for the state update
for (int i = threadIdx.x; i < CH * NS; i += blockDim.x) {
const int s = i / NS;
dlt16[i] = __float2half_rn(__half2float(dlt16[i]) * expf(sg - gcum[(base + s) * HV + hh]));
}
const float sg_exp = expf(sg);
__syncthreads();
#pragma unroll
for (int mi = 0; mi < 2; ++mi)
#pragma unroll
for (int nj = 0; nj < 2; ++nj)
#pragma unroll
for (int q = 0; q < 8; ++q) wF[mi][nj].x[q] *= sg_exp;
{
{
wmma::fragment<wmma::matrix_a, 16, 16, 16, __half, wmma::col_major> aF;
wmma::fragment<wmma::matrix_b, 16, 16, 16, __half, wmma::row_major> bF[2];
for (int kk = 0; kk < CH / 16; ++kk) {
for (int nj = 0; nj < 2; ++nj)
wmma::load_matrix_sync(bF[nj], dlt16 + (size_t) (kk * 16) * NS + 16 * nj, NS);
#pragma unroll
for (int mi = 0; mi < 2; ++mi) {
wmma::load_matrix_sync(aF, Ks + (w * 32 + 16 * mi) + (size_t) (kk * 16) * S, S);
for (int nj = 0; nj < 2; ++nj) wmma::mma_sync(wF[mi][nj], aF, bF[nj], wF[mi][nj]);
}
} }
}
}
// the state slice out through smem as well
#pragma unroll
for (int mi = 0; mi < 2; ++mi)
#pragma unroll
for (int nj = 0; nj < 2; ++nj)
wmma::store_matrix_sync(Ug + (size_t) (w * 32 + 16 * mi) * NS + 16 * nj, wF[mi][nj], NS,
wmma::mem_row_major);
__syncthreads();
for (int i = threadIdx.x; i < S * NS; i += blockDim.x) {
const int r = i / NS, j = i % NS;
state[(size_t) r * HV * S + (size_t) hh * S + j0 + j] = Ug[i];
}
#endif
}
#endif // !HIPCC
// The grow-only workspace, one per (thread, device): a layer split runs the chunked recurrence on more than
// one card, and each card's pointers are only valid on that card - a single per-thread buffer would hand a
// second card the first card's pointers.
struct Ws {
float* A = nullptr; // [SEG][HV][CH][CH]
float* P = nullptr; // [SEG][HV][CH][CH]
float* gcum = nullptr; // [SEG*CH][HV]
size_t cap = 0; // in chunks
void ensure(size_t chunks) {
if (chunks <= cap) return;
if (A) cudaFree(A);
if (P) cudaFree(P);
if (gcum) cudaFree(gcum);
cudaGetLastError(); // a free of another device's pointer must not surface in the mallocs below
cap = chunks;
const size_t mat = chunks * HV * CH * CH;
if (cudaMalloc((void**) &A, mat * sizeof(float)) != cudaSuccess ||
cudaMalloc((void**) &P, mat * sizeof(float)) != cudaSuccess ||
cudaMalloc((void**) &gcum, (size_t) chunks * CH * HV * sizeof(float)) != cudaSuccess) {
int dev = 0;
cudaGetDevice(&dev);
size_t fb = 0, tb = 0;
cudaMemGetInfo(&fb, &tb);
std::fprintf(stderr, "gdn_chunk: workspace alloc failed (%zu chunks, device %d, %.1f of %.1f MiB free): %s\n",
chunks, dev, (double) fb / 1048576.0, (double) tb / 1048576.0,
cudaGetErrorString(cudaGetLastError()));
std::exit(1);
}
}
~Ws() {
// A prompt's stage threads are created per request (std::async in the layer split): without this, each
// request would leak its device's ~50 MB workspace until the card runs out.
if (A) cudaFree(A);
if (P) cudaFree(P);
if (gcum) cudaFree(gcum);
}
};
Ws& ws() {
static thread_local Ws w[8]; // [device]: the cards a layer split can run on in one process
int dev = 0;
if (cudaGetDevice(&dev) != cudaSuccess) {
cudaGetLastError();
dev = 0;
}
if (dev < 0 || dev >= 8) dev = 0;
return w[dev];
}
int gdn_chunk_cc_of(int dev) {
// Per DEVICE: a layer split runs on more than one card, and the capability is a card property - a
// process-global cache would dispatch a second card by the first card's capability.
static int cc[64] = {};
if (dev < 0 || dev >= 64) return 0;
if (cc[dev] == 0) {
cudaDeviceProp p{};
if (cudaGetDeviceProperties(&p, dev) != cudaSuccess) {
cudaGetLastError();
return 0;
}
cc[dev] = p.major * 10 + p.minor;
}
return cc[dev];
}
int gdn_chunk_cc() {
int dev = 0;
if (cudaGetDevice(&dev) != cudaSuccess) {
cudaGetLastError();
return 0;
}
return gdn_chunk_cc_of(dev);
}
} // namespace
bool gdn_chunk_available() {
#if defined(__HIPCC__) || !defined(STRATA_EXPERIMENTAL_SM60)
return false; // the chunked path is compiled and dispatched only in the Volta experimental build
#else
return gdn_chunk_cc() == 70;
#endif
}
void gdn_chunk_recurrence(float* state, const float* h, const float* gate, const float* beta, float* oc,
int64_t T, void* stream) {
#if defined(__HIPCC__)
(void) state; (void) h; (void) gate; (void) beta; (void) oc; (void) T; (void) stream;
std::fprintf(stderr, "gdn_chunk_recurrence: not built for HIP\n");
std::exit(1);
#else
if (T <= 0) return;
const int64_t T64 = T - T % CH;
if (T64 <= 0) return;
cudaStream_t cs = (cudaStream_t) stream;
// the wmma path is the default; STRATA_GDN_CHUNK=2 selects the FP32-only FMA scan (the parity test's
// oracle - same math, no FP16 staging) and anything below sm_70 has no wmma to use. Read per call (the
// tests flip it between launches).
const char* forced_v = std::getenv("STRATA_GDN_CHUNK");
const int forced = forced_v && *forced_v ? std::atoi(forced_v) : -1;
int dev = 0;
if (cudaGetDevice(&dev) != cudaSuccess) {
cudaGetLastError();
dev = 0;
}
#if !defined(__HIPCC__)
const bool wmma_ok = gdn_chunk_cc_of(dev) == 70;
#else
const bool wmma_ok = false;
#endif
// The shared-memory opt-in is a property of the DEVICE's context, not the process: a layer split runs
// this call on more than one card, and each card needs its own cudaFuncSetAttribute before that card's
// past-48KB launches (a process-global std::call_once left the second card at the 48 KB default, and its
// first chunked launch failed with "invalid argument"). Per device, once; every attempt clears the
// runtime error so a refused opt-in cannot surface in a later check() as a spurious failure.
static std::mutex attr_mu;
static bool attr_done[64] = {};
static bool wmma_attr[64] = {};
{
std::lock_guard<std::mutex> lk(attr_mu);
if (dev >= 0 && dev < 64 && !attr_done[dev]) {
const cudaError_t ek = cudaFuncSetAttribute(gdn_chunk_kkt_kernel,
cudaFuncAttributeMaxDynamicSharedMemorySize,
2 * CH * (S + 1) * (int) sizeof(float));
const cudaError_t ew = cudaFuncSetAttribute(gdn_chunk_wmma_kernel,
cudaFuncAttributeMaxDynamicSharedMemorySize, WMMA_SMEM);
cudaGetLastError();
(void) ek; // a refused opt-in leaves the FMA path's own launch to report it
wmma_attr[dev] = ew == cudaSuccess;
attr_done[dev] = true;
}
}
const bool use_wmma = wmma_ok && forced != 2 && dev >= 0 && dev < 64 && wmma_attr[dev];
Ws& w = ws();
const size_t chunks_total = (size_t) (T64 / CH);
w.ensure(chunks_total < SEG ? (chunks_total ? chunks_total : 1) : SEG);
// STRATA_GDN_CHUNK_PROF=1: per-stage milliseconds over the whole call (a dev tool, not a hot path)
static const bool prof = std::getenv("STRATA_GDN_CHUNK_PROF") != nullptr;
cudaEvent_t pe0{}, pe1{};
float ms[3] = {0, 0, 0};
if (prof) cudaEventCreate(&pe0), cudaEventCreate(&pe1);
for (int64_t t0 = 0; t0 < T64; t0 += (int64_t) SEG * CH) {
const int64_t left = (T64 - t0) / CH;
const int nch = (int) (left < SEG ? left : SEG);
const int ntok = nch * CH;
if (prof) cudaEventRecord(pe0, cs);
gdn_chunk_cumsum_kernel<<<dim3((unsigned) nch, HV), CH, 0, cs>>>(w.gcum, gate + t0 * HV, ntok);
check("cumsum");
if (prof) {
cudaEventRecord(pe1, cs);
cudaEventSynchronize(pe1);
cudaEventElapsedTime(&ms[0], pe0, pe1);
cudaEventRecord(pe0, cs);
}
if (use_wmma) {
gdn_chunk_wmma_kernel<<<dim3(NSE, HV), 128, WMMA_SMEM, cs>>>(
state, oc + t0 * HV * S, h + t0 * C, beta + t0 * HV, w.gcum, nch);
check("wmma");
} else {
gdn_chunk_kkt_kernel<<<dim3((unsigned) nch, HV), 128, 2 * CH * (S + 1) * sizeof(float), cs>>>(
w.A, w.P, h + t0 * C, beta + t0 * HV, w.gcum, nch);
check("kkt");
}
if (prof) {
cudaEventRecord(pe1, cs);
cudaEventSynchronize(pe1);
cudaEventElapsedTime(&ms[1], pe0, pe1);
cudaEventRecord(pe0, cs);
}
if (!use_wmma) {
gdn_chunk_fwd_kernel<<<dim3(NSE, HV), 128, 0, cs>>>(state, oc + t0 * HV * S, h + t0 * C, beta + t0 * HV,
w.gcum, w.A, w.P, nch);
check("fwd");
}
if (prof) {
cudaEventRecord(pe1, cs);
cudaEventSynchronize(pe1);
cudaEventElapsedTime(&ms[2], pe0, pe1);
}
}
if (prof) {
std::printf("gdn_chunk prof T=%lld: cumsum %.3fms stage2 %.3fms stage3 %.3fms\n", (long long) T, ms[0],
ms[1], ms[2]);
cudaEventDestroy(pe0);
cudaEventDestroy(pe1);
}
#endif
}
} // namespace strata::prefill
+177 -1
View File
@@ -1,5 +1,6 @@
// src/prefill/kernels.cu - see include/strata/prefill/kernels.hpp.
#include "strata/prefill/kernels.hpp"
#include "strata/prefill/gdn_chunk.hpp"
#include "strata/kernels/mrope.hpp"
#include "strata/kernels/gfx_arch.hpp"
#include "strata/kernels/router_top10.hpp"
@@ -421,6 +422,62 @@ __global__ void gdn_l2_kernel(float* __restrict__ h, float eps) {
x[threadIdx.x] = v * rsqrtf(ss + eps);
}
constexpr int RG = 4, RPG = S / RG;
constexpr int CB = 32, NCB = S / CB; // value columns per block kernel / blocks per head
// v100/gdn-chunk: Volta-only (sm_70), inside the experimental build. Main's recurrence kernels above are
// untouched for every other architecture; the chain-split is dispatched only when the device is cc 7.0.
#if defined(STRATA_EXPERIMENTAL_SM60)
// v100/gdn-chunk: the same recurrence with WARP-LOCAL reductions - no __syncthreads at all. gdn_rec_cols_*'
// per-token shape is two cross-warp reductions (k^T W and q^T W) behind two barriers each (six barriers per
// token in the pipelined kernel); here a warp owns 8 columns and the 4 row-groups are lanes within the warp,
// so the reductions are __shfl's. The arithmetic is the same expressions in the same order - the four
// row-group partials still sum as ((p0+p1)+p2)+p3 - so this kernel is BIT-EXACT against gdn_rec_cols_pipe
// (the parity test asserts it). The state has the same (S, h_v, S) layout and the same j-fastest column.
__global__ void __launch_bounds__(S) gdn_rec_cols_warp_kernel(float* __restrict__ state, const float* __restrict__ h,
const float* __restrict__ gate,
const float* __restrict__ beta,
float* __restrict__ oc_out, int64_t T) {
const int head = blockIdx.x / NCB, cb = blockIdx.x % NCB;
const int w = threadIdx.x >> 5, l = threadIdx.x & 31; // warp w: columns w*8..w*8+7
const int col = cb * CB + w * 8 + (l & 7); // lane: column within the warp's 8
const int rg = l >> 3; // lane group: 4 row-groups of 32 rows
const int qh = head % HK;
float s[RPG];
float* base = state + ((size_t) (rg * RPG) * HV + head) * S + col;
const size_t rs = (size_t) HV * S;
#pragma unroll
for (int r = 0; r < RPG; ++r) s[r] = base[r * rs];
const unsigned full = 0xffffffffu;
for (int64_t t = 0; t < T; ++t) {
const float* ht = h + t * C;
const float* krow = ht + HK * S + qh * S + rg * RPG;
const float* qrow = ht + qh * S + rg * RPG;
float kv = 0.0f;
#pragma unroll
for (int r = 0; r < RPG; ++r) kv = fmaf(s[r], krow[r], kv);
// ((p0 + p1) + p2) + p3 over the row-groups, exactly as red[0]+red[1]+red[2]+red[3]
float p0 = __shfl_sync(full, kv, (l & 7));
float p1 = __shfl_sync(full, kv, (l & 7) + 8);
float p2 = __shfl_sync(full, kv, (l & 7) + 16);
float p3 = __shfl_sync(full, kv, (l & 7) + 24);
const float kv_col = ((p0 + p1) + p2) + p3;
const float g = __expf(gate[t * HV + head]);
const float delta = (ht[2 * HK * S + head * S + col] - g * kv_col) * beta[t * HV + head];
float o = 0.0f;
#pragma unroll
for (int r = 0; r < RPG; ++r) {
s[r] = fmaf(g, s[r], krow[r] * delta);
o = fmaf(s[r], qrow[r], o);
}
float q0 = __shfl_sync(full, o, (l & 7));
float q1 = __shfl_sync(full, o, (l & 7) + 8);
float q2 = __shfl_sync(full, o, (l & 7) + 16);
float q3 = __shfl_sync(full, o, (l & 7) + 24);
oc_out[t * HV * S + head * S + col] = (((q0 + q1) + q2) + q3) * rsqrtf((float) S);
}
#pragma unroll
for (int r = 0; r < RPG; ++r) base[r * rs] = s[r];
}
#endif
__global__ void __launch_bounds__(S * RG) gdn_rec_kernel(float* __restrict__ state, const float* __restrict__ h,
const float* __restrict__ gate,
const float* __restrict__ beta, const float* __restrict__ z,
@@ -481,7 +538,7 @@ __global__ void __launch_bounds__(S * RG) gdn_rec_kernel(float* __restrict__ sta
// quarter of its threads per __syncthreads), and the output norm - the only step that couples the head's columns -
// in its own kernel. Per column the same arithmetic in the same order (the 4 row-group partial sums added as
// red[0] + red[1] + red[2] + red[3]; the norm's warp sums over the same 32-column warps): the same bits.
constexpr int CB = 32, NCB = S / CB;
__global__ void __launch_bounds__(CB * RG) gdn_rec_cols_kernel(float* __restrict__ state, const float* __restrict__ h,
const float* __restrict__ gate,
const float* __restrict__ beta,
@@ -581,6 +638,71 @@ __global__ void __launch_bounds__(CB * RG) gdn_rec_cols_pipe_kernel(float* __res
#pragma unroll
for (int r = 0; r < RPG; ++r) base[r * rs] = s[r];
}
// v100/gdn-chunk: gdn_rec_cols_pipe_kernel with the two 32-deep FMA chains (k^T W and q^T W) split into 4
// accumulators each. The chain is the recurrence's per-token floor (a 32-step dependent FFMA chain is ~128
// cycles before the barriers); the split keeps the load pattern, the barriers and the (S, h_v, S) state
// layout untouched. FP32-level, NOT bit-exact - the four partial sums group the 32 products differently -
// so it is opt-in by measured benefit (STRATA_GDN_REC_WARP=2; gdn_chunk_parity bounds the error).
#if defined(STRATA_EXPERIMENTAL_SM60)
__global__ void __launch_bounds__(CB * RG) gdn_rec_cols_pipe_fast_kernel(float* __restrict__ state,
const float* __restrict__ h,
const float* __restrict__ gate,
const float* __restrict__ beta,
float* __restrict__ oc_out, int64_t T) {
constexpr int NT = CB * RG, LPT = S / NT;
__shared__ float sk[S], sq[S], red[RG][CB];
const int head = blockIdx.x / NCB, cb = blockIdx.x % NCB;
const int c = threadIdx.x, rg = threadIdx.y, tid = rg * CB + c, col = cb * CB + c;
const int qh = head % HK;
float s[RPG];
float* base = state + ((size_t) (rg * RPG) * HV + head) * S + col;
const size_t rs = (size_t) HV * S;
#pragma unroll
for (int r = 0; r < RPG; ++r) s[r] = base[r * rs];
float nq[LPT], nk[LPT], nv = 0.0f, ng = 0.0f, nb = 0.0f;
auto fetch = [&](int64_t t) {
const float* ht = h + t * C;
#pragma unroll
for (int u = 0; u < LPT; ++u) { nq[u] = ht[qh * S + tid + u * NT]; nk[u] = ht[HK * S + qh * S + tid + u * NT]; }
nv = ht[2 * HK * S + head * S + col];
ng = gate[t * HV + head];
nb = beta[t * HV + head];
};
if (T > 0) fetch(0);
for (int64_t t = 0; t < T; ++t) {
float cq[LPT], ck[LPT];
#pragma unroll
for (int u = 0; u < LPT; ++u) { cq[u] = nq[u]; ck[u] = nk[u]; }
const float cv = nv, cg = ng, cbt = nb;
__syncthreads();
#pragma unroll
for (int u = 0; u < LPT; ++u) { sq[tid + u * NT] = cq[u]; sk[tid + u * NT] = ck[u]; }
__syncthreads();
if (t + 1 < T) fetch(t + 1);
const float g = __expf(cg);
float kv[4] = {0.0f, 0.0f, 0.0f, 0.0f};
#pragma unroll
for (int r = 0; r < RPG; ++r) kv[r & 3] = fmaf(s[r], sk[rg * RPG + r], kv[r & 3]);
red[rg][c] = (kv[0] + kv[1]) + (kv[2] + kv[3]);
__syncthreads();
const float kv_col = red[0][c] + red[1][c] + red[2][c] + red[3][c];
const float delta = (cv - g * kv_col) * cbt;
float o[4] = {0.0f, 0.0f, 0.0f, 0.0f};
#pragma unroll
for (int r = 0; r < RPG; ++r) {
s[r] = fmaf(g, s[r], sk[rg * RPG + r] * delta);
o[r & 3] = fmaf(s[r], sq[rg * RPG + r], o[r & 3]);
}
__syncthreads();
red[rg][c] = (o[0] + o[1]) + (o[2] + o[3]);
__syncthreads();
if (rg == 0) oc_out[t * HV * S + head * S + col] = (red[0][c] + red[1][c] + red[2][c] + red[3][c]) * rsqrtf((float) S);
}
#pragma unroll
for (int r = 0; r < RPG; ++r) base[r * rs] = s[r];
}
#endif
#if !defined(__HIPCC__)
// The recurrence with one thread for the three value heads that share a key head (head % HK): column c of heads
// qh, qh + 16 and qh + 32, row group rg. gdn_rec_cols_pipe_kernel spends its time in shared memory, not in
@@ -1923,6 +2045,17 @@ __global__ void swiglu_il_kernel(const float* __restrict__ gu, uint16_t* __restr
const float g = gu[r * 1280 + 2 * k], u = gu[r * 1280 + 2 * k + 1];
h16[i] = hf_sat(g / (1.0f + __expf(-g)) * u);
}
// The Volta prompt experts (gemm_iq_f16_grouped): SwiGLU of the gate/up product's rows (gate 0..n_ff, up n_ff..2 n_ff,
// or interleaved) to the FP16 input of the down product, saturated as swiglu_il_kernel
__global__ void swiglu_split_f16_kernel(const float* __restrict__ gu, uint16_t* __restrict__ h16, int64_t rows, int n_ff,
bool interleaved) {
const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
if (i >= rows * n_ff) return;
const int64_t r = i / n_ff, k = i % n_ff;
const float* row = gu + r * 2 * n_ff;
const float g = interleaved ? row[2 * k] : row[k], u = interleaved ? row[2 * k + 1] : row[n_ff + k];
h16[i] = hf_sat(g / (1.0f + __expf(-g)) * u);
}
__global__ void swiglu_pair_kernel(const float* __restrict__ g, const float* __restrict__ u, uint16_t* __restrict__ h16,
int64_t n) {
const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
@@ -2529,6 +2662,44 @@ void gdn_recurrence_variant(int variant, float* state, const float* h, const flo
}
#else
(void) variant; // the quad recurrence kernels are AMD-only
#endif
#if defined(STRATA_EXPERIMENTAL_SM60)
// v100/gdn-chunk: the chunked recurrence (src/prefill/gdn_chunk.cu) on Volta, where the token chain is the
// cost. STRATA_GDN_CHUNK=0 forces the recurrence, =1 forces the chunked path (the parity test's A/B switch);
// unset: cc == 7.0 only, every other architecture keeps the recurrence bit-for-bit as before. Read per call
// on purpose - cheap next to the work, and the tests flip it between two launches.
const char* chunk_v = std::getenv("STRATA_GDN_CHUNK");
const int chunk_env = chunk_v && *chunk_v ? std::atoi(chunk_v) : -1;
static const bool volta = gdn_chunk_available(); // runtime cc == 7.0 (the kernels are compiled for sm_70 only)
const bool chunked = !serial && T > 0 && (chunk_env >= 0 ? chunk_env != 0 : false);
// v100/gdn-chunk: the sync-free warp-reduction recurrence (bit-exact vs gdn_rec_cols_pipe) is the
// measured-fast path on Volta; the chunked recurrence is opt-in (STRATA_GDN_CHUNK=1/2) - correct and
// measured, but slower than this on the V100 (bench/gdn_chunk_bench). STRATA_GDN_REC_WARP=0 restores
// the old pipelined kernel bit-for-bit.
// STRATA_GDN_REC_WARP (Volta only, opt-in): unset or 0 -> the pipelined kernel (the default; the chain split changes the
// summation order, so it is not the default without a V100 check here), 2 -> the chain-split kernel (measured +6..9%, FP32-level), the
// old pipelined kernel bit-for-bit is 0, 1 -> the sync-free bit-exact control.
const char* warp_v = std::getenv("STRATA_GDN_REC_WARP");
const int warp_env = warp_v && *warp_v ? std::atoi(warp_v) : 0;
const bool warp_rec = !serial && !chunked && T > 0 && volta && warp_env != 0;
if (chunked && T >= 64) {
// the chunked prefix + the recurrence over the tail (< 64 tokens), then the out norm over all of T
const int64_t T64 = T - T % 64;
gdn_chunk_recurrence(state, h, gate, beta, y, T64, stream);
if (T > T64)
gdn_rec_cols_pipe_kernel<<<HV * NCB, dim3(CB, RG), 0, (cudaStream_t) stream>>>(
state, h + T64 * C, gate + T64 * HV, beta + T64 * HV, y + T64 * (size_t) HV * S, T - T64);
gdn_out_norm_kernel<<<dim3((unsigned) T, HV), S, 0, (cudaStream_t) stream>>>(z, gamma, eps, y, y16, ld16);
} else if (warp_rec) {
// =2: the 4-accumulator chain split on the pipelined structure (FP32-level, not bit-exact);
// =1: the sync-free bit-exact warp reduction (measured slower - kept as the bitwise control)
if (warp_env == 2)
gdn_rec_cols_pipe_fast_kernel<<<HV * NCB, dim3(CB, RG), 0, (cudaStream_t) stream>>>(state, h, gate, beta,
y, T);
else
gdn_rec_cols_warp_kernel<<<HV * NCB, S, 0, (cudaStream_t) stream>>>(state, h, gate, beta, y, T);
gdn_out_norm_kernel<<<dim3((unsigned) T, HV), S, 0, (cudaStream_t) stream>>>(z, gamma, eps, y, y16, ld16);
} else
#endif
if (serial || T <= 0 || variant == 2) {
gdn_rec_kernel<<<HV, dim3(S, RG), 0, (cudaStream_t) stream>>>(state, h, gate, beta, z, gamma, eps, y, y16, T, ld16);
@@ -2582,6 +2753,11 @@ void swiglu_interleaved(const float* gu, uint16_t* h16, int64_t n, void* stream)
swiglu_il_kernel<<<blocks_for(n * 640), 256, 0, (cudaStream_t) stream>>>(gu, h16, n);
check("swiglu_interleaved");
}
void swiglu_split_f16(const float* gu, uint16_t* h16, int64_t rows, int n_ff, bool interleaved, void* stream) {
if (rows <= 0) return;
swiglu_split_f16_kernel<<<blocks_for(rows * n_ff), 256, 0, (cudaStream_t) stream>>>(gu, h16, rows, n_ff, interleaved);
check("swiglu_split_f16");
}
void swiglu_pair(const float* g, const float* u, uint16_t* h16, int64_t n, void* stream) {
swiglu_pair_kernel<<<blocks_for(n * 640), 256, 0, (cudaStream_t) stream>>>(g, u, h16, n);
check("swiglu_pair");
+77 -12
View File
@@ -1123,6 +1123,7 @@ constexpr size_t MMQ_TAIL = 4096;
struct MmqPlan {
bool any = false, fallback = true;
std::vector<char> layer; // per layer: MMQ
std::vector<char> wmma_only; // per layer: in the MMQ grouping for the WMMA tiles only (pf_wmma: IQ1_M)
std::vector<char> fo; // per layer: no MMQ here but the native fused kernels cover its formats
// (gfx11: UD-Q4_K_XL's Q4_K / Q5_K and Q5_1 / Q8_0 experts, STRATA_PF_FUSED=1)
size_t gu_max = 0, d_max = 0;
@@ -1134,6 +1135,30 @@ struct MmqPlan {
// launches run whole tiles on every visible GPU (mmq::whole_tiles), so its full groups may be taken in row-count order
std::vector<char> group_sort;
};
// Volta (sm_70): MMQ runs on dp4a there (no int8 tensor cores). pf_wmma(): the layers MMQ would take, and the IQ1_M
// ones the FP16 path would, run as one launch per expert group on FP16 tensor-core tiles instead
// (strata::kernels::gemm_iq_f16_grouped: each weight superblock dequantized once into shared memory by the FP16 path's
// own formulas, FP16 activations, FP32 sums). OPT-IN: STRATA_PF_WMMA=1 (the activations are FP16 rather than MMQ's
// q8_1, so the answers differ from the default). Only when EVERY visible CUDA card is compute capability 7.0 or
// newer: the tiles need tensor cores, and a Volta + Pascal rig (one process, one decision) keeps MMQ.
bool pf_wmma() {
#if defined(__HIPCC__)
return false;
#else
static const bool on = [] {
const char* e = std::getenv("STRATA_PF_WMMA");
if (e == nullptr || e[0] != '1') return false;
int n = 0;
if (cudaGetDeviceCount(&n) != cudaSuccess || n <= 0) return false;
for (int d = 0; d < n; ++d) {
int major = 0;
if (cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, d) != cudaSuccess || major < 7) return false;
}
return true;
}();
return on;
#endif
}
const MmqPlan& mmq_plan() {
static const MmqPlan plan = [] {
MmqPlan p;
@@ -1143,11 +1168,21 @@ const MmqPlan& mmq_plan() {
const int64_t layers = lay.native ? (int64_t) lay.fmt.size() : lay.n_layers;
p.layer.assign((size_t) std::max<int64_t>(layers, 0), 0);
p.fo.assign(p.layer.size(), 0);
p.wmma_only.assign(p.layer.size(), 0);
p.fallback = !on || layers <= 0;
for (int64_t l = 0; on && l < layers; ++l) {
const int gt = lay.native ? lay.fmt[(size_t) l].gu_type : 42, dt = lay.native ? lay.fmt[(size_t) l].d_type : 42;
// #420: a tile on every GPU for these shapes (gate+up: 1280 rows, down: N rows), else the FP16 path
if (!mmq::fits(gt, 1280) || !mmq::fits(dt, N)) {
// pf_wmma: a format dq_dispatch takes (IQ1_M, an IQ4_NL down) rides the MMQ grouping, computed by the WMMA tiles only
if (pf_wmma() && lay.native && (dt == 42 || dt == 20) && strata::kernels::iq_row_bytes(gt, N) > 0) {
p.layer[(size_t) l] = 1;
p.wmma_only[(size_t) l] = 1;
p.any = true;
p.gu_max = std::max(p.gu_max, mmq::matrix_bytes(gt, 1280, N));
p.d_max = std::max(p.d_max, mmq::matrix_bytes(dt, N, 640));
continue;
}
p.fallback = true;
// the fused path's buffers (Xq, H) exist for it; a chunk it does not take (a small one) keeps the FP16 path
if (on && lay.native && fused::native_supported(gt, dt)) { p.fo[(size_t) l] = 1; p.any = true; }
@@ -1197,6 +1232,8 @@ const MmqPlan& mmq_plan() {
}();
return plan;
}
// the FP16 buffers (Xs, Hh): the FP16 path's, or pf_wmma's activations and down input
bool fp16_bufs(const MmqPlan& mp) { return mp.fallback || pf_wmma(); }
// #136 P3: a layout whose chunks run the fused experts (STRATA_PF_FUSED=1, the Q2_0 pack, a streamed chunk of
// stream_all_min() tokens or more). Its GU, H and Xq hold only the fused path's grouping tables, int8 H and per-token
// int8 activations, and Hq nothing: ~100 KB a token less than MMQ's FP32 GU / H and per-slot q8_1 rows, which is what
@@ -1223,9 +1260,9 @@ uint64_t moe_set_bytes(size_t T, int64_t n_expert, bool fused) {
Alloc a; a.count_only = true; bool ok = true;
a.take<float>(T * n_expert, ok); a.take<float>(T * K, ok); a.take<int32_t>(T * K, ok); a.take<int32_t>(T * K, ok);
a.take<int32_t>(T * K, ok);
if (mp.fallback) a.take<uint16_t>(T * K * N, ok);
if (fp16_bufs(mp)) a.take<uint16_t>(T * K * N, ok);
a.take<float>(mb.gu, ok);
if (mp.fallback) a.take<uint16_t>(T * K * 640, ok);
if (fp16_bufs(mp)) a.take<uint16_t>(T * K * 640, ok);
a.take<float>(T * K * N, ok); a.take<float>(T * 640, ok);
a.take<float>(T * 640, ok); a.take<uint16_t>(T * 640, ok); a.take<float>(T * N, ok); a.take<float>(T, ok);
if (mp.any) {
@@ -1487,9 +1524,9 @@ bool Prefill::carve(size_t T, void* alloc) {
m.logits = c.take<float>(T * m.g->n_expert, ok); m.w = c.take<float>(T * K, ok); m.ids = c.take<int32_t>(T * K, ok);
m.slot_dev = c.take<int32_t>(T * K, ok); m.src_dev = c.take<int32_t>(T * K, ok);
const MmqPlan& mp = mmq_plan();
m.Xs = mp.fallback ? c.take<uint16_t>(T * K * N, ok) : nullptr;
m.Xs = fp16_bufs(mp) ? c.take<uint16_t>(T * K * N, ok) : nullptr;
m.GU = c.take<float>(mb.gu, ok);
m.Hh = mp.fallback ? c.take<uint16_t>(T * K * 640, ok) : nullptr;
m.Hh = fp16_bufs(mp) ? c.take<uint16_t>(T * K * 640, ok) : nullptr;
m.Dm = c.take<float>(T * K * N, ok);
m.sgate = c.take<float>(T * 640, ok); m.sup = c.take<float>(T * 640, ok); m.sh_h = c.take<uint16_t>(T * 640, ok);
m.shared = c.take<float>(T * N, ok); m.sg = c.take<float>(T, ok);
@@ -3867,6 +3904,14 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
return true;
});
}
// pf_wmma: this layer's groups on the FP16 tensor-core tiles (single GPU, native pack, Q2_0 / IQ4_NL down)
const bool wmma_l = use_mmq && pf_wmma() && !fused_l && on_peer.empty() && lay.native &&
(mmq_dt == 42 || mmq_dt == 20) && !lay.fmt[(size_t) l].tail_off &&
strata::kernels::iq_row_bytes(mmq_gt, N) > 0;
if (use_mmq && mmq_plan().wmma_only[(size_t) l] && !wmma_l) {
err = "prefill: an IQ1_M layer in the MMQ grouping needs the WMMA tiles, which this chunk cannot take";
return false;
}
const size_t mmq_gub = use_mmq ? mmq::matrix_bytes(mmq_gt, 1280, N) : 0;
const size_t mmq_db = use_mmq ? mmq::matrix_bytes(mmq_dt, N, 640) : 0;
pt.mark(kPfGather, cs);
@@ -3878,14 +3923,19 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
// from its rotated copy `Xr`): each token quantized once and written to its K rows
// (slot_dev, the inverse of src_dev).
// NVFP4 w4a4 activations carry a per-row scale (Xscale): that mode keeps the gather.
if (had_gu) {
strata::kernels::hadamard_rows(m.mixed, m.Xr, T, N, had_block, had_sx, m.cs);
xsrc = m.Xr;
if (wmma_l) { // FP16 rows (pf_wmma); APR: Hadamard-folded gate/up take H, rotated in fp16 storage as the FP16 path does
gather_rows16(m.mixed_h, m.src_dev, m.Xs, T * K, N, m.cs);
if (had_gu) strata::kernels::hadamard_rows_f16(m.Xs, T * K, N, had_block, had_sx, m.cs);
} else {
if (had_gu) {
strata::kernels::hadamard_rows(m.mixed, m.Xr, T, N, had_block, had_sx, m.cs);
xsrc = m.Xr;
}
if (mmq::fp4_activations(mmq_gt))
mmq::quantize(xsrc, m.src_dev, m.Xq, mmq_gt, N, N, T * K, m.cs, m.Xscale);
else
mmq::quantize_scatter(xsrc, m.slot_dev, m.src_dev, m.Xq, mmq_gt, N, N, T, (int) K, m.cs);
}
if (mmq::fp4_activations(mmq_gt))
mmq::quantize(xsrc, m.src_dev, m.Xq, mmq_gt, N, N, T * K, m.cs, m.Xscale);
else
mmq::quantize_scatter(xsrc, m.slot_dev, m.src_dev, m.Xq, mmq_gt, N, N, T, (int) K, m.cs);
// each group's rows: absolute bounds (gate/up reads the layer's rows), relative ones (down
// reads the group's own quantized H)
const size_t n = order.size(), ng = (n + MMQ_GROUP - 1) / MMQ_GROUP;
@@ -4287,7 +4337,7 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
// STRATA_MMQ_DIRECT=1: a resident expert with guard room in its slot is not gathered - the
// group's pointer tables give MMQ each expert's own address (group position q), the others are
// gathered at compact positions c = 0..ns-1 of the group buffers, as before (same bytes)
const bool direct = use_mmq && lay.native && m.cache && mmq_plan().direct[(size_t) l];
const bool direct = use_mmq && lay.native && m.cache && mmq_plan().direct[(size_t) l] && !wmma_l;
mmq::WeightTab tgu, td;
mmq::GuardTab gd;
int ns = 0;
@@ -4394,6 +4444,21 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
int64_t maxr = 0;
for (size_t i = j0; i <= j; ++i) maxr = std::max<int64_t>(maxr, m.cnt[(size_t) order[i]]);
pt.mark(kPfGemmGU, cs);
if (wmma_l) { // pf_wmma: gate/up, SwiGLU to FP16, down - the group in 2 tile launches
const int32_t* dnb = m.bounds_dev + n + 1 + g * (MMQ_GROUP + 1);
const bool ok1 = strata::kernels::gemm_iq_f16_grouped(
mmq_gt, m.grp_gu, mmq_gub, 1280, (int) N, m.Xs, (int) N, m.bounds_dev + j0, ngx,
(int) maxr, m.GU, 1280, m.cs);
swiglu_split_f16(m.GU + r0 * 1280, m.Hh + r0 * 640, nr, 640, !lay.native, m.cs);
if (had_d) // APR: folded down weights take H (s * h), rotated in fp16 storage as the FP16 path does
strata::kernels::hadamard_rows_f16(m.Hh + r0 * 640, nr, 640, had_block, had_sh, m.cs);
pt.mark(kPfGemmD, cs);
const bool ok2 = strata::kernels::gemm_iq_f16_grouped(
mmq_dt, m.grp_d, mmq_db, (int) N, 640, m.Hh + r0 * 640, 640, dnb, ngx, (int) maxr,
m.Dm + r0 * N, (int) N, m.cs);
if (!ok1 || !ok2) { err = "prefill: the WMMA expert tiles could not launch"; return false; }
return true;
}
if (direct) {
// one launch: the direct experts' guards (their down over-read) and the zeroed tail
// after the last gathered expert (see MMQ_TAIL)
+168
View File
@@ -0,0 +1,168 @@
"""tools/q8_dense_gguf.py - a copy of a model whose natively served dense projections and head are Q8_0, for the
Pascal GP100 decode kernel (STRATA_Q8_SM60=1, docs/OLDER_GPUS.md).
The GSQ-RCO packs keep those matrices in K- and i-quants (Q6_K, IQ4_XS, Q4_K, IQ3_S, Q5_K, Q2_0, IQ4_NL), whose
decode is what a GP100 die is slowest at; STRATA_Q8_SM60 only runs Q8_0 matrices. Every shard of the model is
handled, because a model may keep dense matrices in more than one (Swift 1.5 IQ3_XXS: 78 in shard 1, 223 in
shard 2). A shard that holds any of them is written as:
* the tensor-info block with the SAME byte length: names and dims are unchanged, only the u32 type and the u64
offset of each converted tensor change, so the data section starts where it did and every other tensor - the
routed experts above all - keeps its absolute offset. An existing native pack (its native_experts.txt) stays
valid; nothing is repacked.
* the original data section, then each converted tensor's Q8_0 blocks appended (the old bytes stay, unused).
Qwen3.8-Flash-Next IQ3_XXS: 301 tensors, +3.5 GiB, the worst requantization error 0.41% of a tensor's |w|max
(Q8_0 is finer than every source format).
A shard that holds none is hard-linked into the output folder (--copy copies it): the engine finds the shards beside
--native, so --native and --ple-gguf must both name files in the new folder (it refuses two shard 2s).
python tools/q8_dense_gguf.py <folder>/<model>-00001-of-00002.gguf <new folder> [--copy]
Any shard of the model may be named. Then point the config's --native and --ple-gguf at the new folder and run the
engine with STRATA_Q8_SM60=1.
"""
from __future__ import annotations
import argparse
import os
import re
import shutil
import struct
import sys
import time
from pathlib import Path
import numpy as np
sys.path.insert(0, str(Path(__file__).resolve().parent))
import _paths # noqa: E402
_paths.add_gguf_py()
from gguf import GGUFReader, GGMLQuantizationType as QT # noqa: E402
from gguf.quants import dequantize, quantize # noqa: E402
from gguf_writer import dequantize_q2_0 # noqa: E402
# what src/core/native_dense.cpp serves natively (eligible()), and the head
SUFFIXES = (".attn_qkv.weight", ".attn_gate.weight", ".ssm_out.weight", ".attn_q.weight", ".attn_k.weight",
".attn_v.weight", ".attn_output.weight", ".ffn_gate_shexp.weight", ".ffn_up_shexp.weight",
".ffn_down_shexp.weight")
Q2_0 = 42 # GSQ's 2-bit type: gguf-py has no member for it
def is_target(name: str) -> bool:
return name == "output.weight" or (name.startswith("blk.") and name.endswith(SUFFIXES))
def to_f32(t) -> np.ndarray:
ne0, ne1 = int(t.shape[0]), int(t.shape[1])
raw = np.asarray(t.data)
if int(t.tensor_type) == Q2_0:
return np.asarray(dequantize_q2_0(raw.tobytes()), dtype=np.float32).reshape(ne1, ne0)
return np.asarray(dequantize(raw, t.tensor_type), dtype=np.float32).reshape(ne1, ne0)
def shards_of(path: Path) -> list[Path]:
"""Every shard of the model `path` belongs to (just `path` for an unsplit file)."""
m = re.match(r"(.*-)(\d{5})-of-(\d{5})(\.gguf)$", path.name)
if not m:
return [path]
return [path.parent / f"{m[1]}{k:05d}-of-{m[3]}{m[4]}" for k in range(1, int(m[3]) + 1)]
def jobs_of(r) -> list:
"""The shard's convertible tensors and where each one's type/offset fields sit in its tensor-info block."""
data_start, mm, jobs = r.data_offset, r.data, []
for t in r.tensors:
if not is_target(t.name) or int(t.tensor_type) == int(QT.Q8_0):
continue
p = t.field.offset # the tensor-info entry: name, n_dims, dims, type, offset
nlen = struct.unpack_from("<Q", mm, p)[0]; p += 8
assert bytes(mm[p:p + nlen]).decode() == t.name; p += nlen
ndim = struct.unpack_from("<I", mm, p)[0]; p += 4 + 8 * ndim
ttype, toff = struct.unpack_from("<IQ", mm, p)
assert ttype == int(t.tensor_type) and data_start + toff == t.data_offset, t.name
if int(t.shape[0]) % 32:
print(f" {t.name}: rows of {int(t.shape[0])} are not whole Q8_0 blocks, kept")
continue
jobs.append((t, p))
return jobs
def convert(src: Path, dst: Path, r, jobs) -> int:
t0 = time.time()
align, data_start, src_size = r.alignment, r.data_offset, os.path.getsize(src)
blobs, worst = [], 0.0
for t, p in jobs:
f = to_f32(t)
q = np.ascontiguousarray(quantize(f, QT.Q8_0)).view(np.uint8).reshape(-1)
assert q.nbytes == int(t.shape[0]) // 32 * 34 * int(t.shape[1]), t.name
back = dequantize(q, QT.Q8_0).reshape(f.shape)
worst = max(worst, float(np.abs(back - f).max() / max(float(np.abs(f).max()), 1e-30)))
blobs.append((t, p, q))
print(f" converted in {time.time() - t0:.0f} s; worst requantization error {worst:.2e} of a tensor's |w|max; "
f"{sum(b[2].nbytes for b in blobs) / 2**30:.2f} GiB to append", flush=True)
tmp = dst.with_name(dst.name + ".part")
shutil.copyfile(src, tmp)
with open(tmp, "r+b") as fh:
end = src_size
for t, p, blob in blobs:
at = (end + align - 1) // align * align
fh.seek(end); fh.write(b"\0" * (at - end))
fh.seek(at); fh.write(blob.tobytes())
end = at + blob.nbytes
fh.seek(p); fh.write(struct.pack("<IQ", int(QT.Q8_0), at - data_start))
fh.flush(); os.fsync(fh.fileno())
os.replace(tmp, dst)
v = GGUFReader(dst) # every other tensor where it was, every new one as written
conv = {t.name: blob for t, _, blob in blobs}
orig = {t.name: t for t in r.tensors}
assert len(v.tensors) == len(r.tensors) and v.data_offset == data_start
for t in v.tensors:
if t.name in conv:
assert t.tensor_type == QT.Q8_0 and np.array_equal(np.asarray(t.data).view(np.uint8).reshape(-1), conv[t.name]), t.name
else:
assert t.tensor_type == orig[t.name].tensor_type and t.data_offset == orig[t.name].data_offset, t.name
print(f" wrote {dst} ({os.path.getsize(dst) / 2**30:.2f} GiB): {len(conv)} converted, {len(v.tensors) - len(conv)} "
"untouched, offsets checked", flush=True)
return len(conv)
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
ap.add_argument("shard", type=Path, help="any GGUF shard of the model (or the model's only file)")
ap.add_argument("out_dir", type=Path, help="folder for the converted shards and the others' links")
ap.add_argument("--copy", action="store_true", help="copy the shards with nothing to convert instead of linking them")
a = ap.parse_args()
out = a.out_dir.resolve()
shards = shards_of(a.shard.resolve())
if out == shards[0].parent:
sys.exit("the output folder must not be the model's own folder")
missing = [s for s in shards if not s.is_file()]
if missing:
sys.exit(f"missing shard(s): {', '.join(str(s) for s in missing)}")
out.mkdir(parents=True, exist_ok=True)
total = 0
for src in shards:
dst = out / src.name
r = GGUFReader(src)
jobs = jobs_of(r)
print(f"{src.name}: {len(r.tensors)} tensors, {len(jobs)} to convert to Q8_0", flush=True)
if jobs:
total += convert(src, dst, r, jobs)
continue
if dst.exists():
dst.unlink() # a link or copy from an earlier run
if a.copy:
shutil.copyfile(src, dst)
else:
os.link(src, dst)
print(f" {'copied' if a.copy else 'linked'} (nothing to convert)", flush=True)
print(f"{total} tensors converted over {len(shards)} shard(s) in {out}")
return 0
if __name__ == "__main__":
sys.exit(main())
+108
View File
@@ -0,0 +1,108 @@
// tools/q8_sm60_check.cu - parity and speed of the STRATA_Q8_SM60=1 kernel (src/kernels/cuda/q8_sm60.cuh) on the
// Q8_0 shapes of Qwen3.8-Flash-Next (hidden 2560): the dense projections, the shared expert and the head.
//
// It includes the committed header, so the check covers the code the engine compiles, not a copy. Parity: random
// Q8_0 weights in GGUF blocks -> q8sm60::pack_kernel -> the kernel, against a CPU double reference of
// sum over blocks of d_w * d_x * dot_int8, for 1..8 columns (max relative error < 1e-5). Speed: a 1 GiB rotation so
// the weights come from DRAM, as in the engine. No CMake target; build by hand:
//
// nvcc -O3 -arch=sm_60 -std=c++17 -Iinclude -Isrc/kernels/cuda tools/q8_sm60_check.cu -o q8_sm60_check && ./q8_sm60_check
//
// Exit status 0 = every case within tolerance and no CUDA error.
#include <cuda_fp16.h>
#include <cuda_runtime.h>
#include <algorithm>
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <vector>
#define CK(x) do { cudaError_t e_ = (x); if (e_ != cudaSuccess) { printf("CUDA %s at %d\n", cudaGetErrorString(e_), __LINE__); exit(1); } } while (0)
struct Q81Block { half2 ds; int8_t qs[32]; };
struct Q80Block { half d; int8_t qs[32]; };
#include "strata/kernels/dp4a.hpp"
#include "q8_sm60.cuh"
static float h2f(half h) { return __half2float(h); }
static bool parity(int n_in, int n_out, int ncols) {
const int nb = n_in / 32;
std::vector<Q80Block> w((size_t) n_out * nb);
std::vector<Q81Block> x((size_t) ncols * nb);
srand(n_in * 7 + n_out + ncols);
for (auto& b : w) { b.d = __float2half((rand() % 1000 + 1) * 1e-5f); for (auto& q : b.qs) q = (int8_t) (rand() % 255 - 127); }
for (auto& b : x) { b.ds = __halves2half2(__float2half((rand() % 1000 + 1) * 1e-4f), __float2half(0.f)); for (auto& q : b.qs) q = (int8_t) (rand() % 255 - 127); }
std::vector<double> ref((size_t) ncols * n_out);
for (int j = 0; j < ncols; ++j) for (int r = 0; r < n_out; ++r) {
double s = 0;
for (int b = 0; b < nb; ++b) {
const Q80Block& wb = w[(size_t) r * nb + b]; const Q81Block& xb = x[(size_t) j * nb + b];
int dot = 0; for (int i = 0; i < 32; ++i) dot += wb.qs[i] * xb.qs[i];
s += (double) h2f(wb.d) * __low2float(xb.ds) * dot;
}
ref[(size_t) j * n_out + r] = s;
}
Q80Block* dw; Q81Block* dx; float* dy; int8_t* qs;
CK(cudaMalloc(&dw, w.size() * sizeof(Q80Block))); CK(cudaMemcpy(dw, w.data(), w.size() * sizeof(Q80Block), cudaMemcpyHostToDevice));
CK(cudaMalloc(&dx, x.size() * sizeof(Q81Block))); CK(cudaMemcpy(dx, x.data(), x.size() * sizeof(Q81Block), cudaMemcpyHostToDevice));
CK(cudaMalloc(&dy, ref.size() * 4)); CK(cudaMemset(dy, 0xff, ref.size() * 4));
const size_t count = (size_t) n_out * nb;
CK(cudaMalloc(&qs, count * 34));
half* d = reinterpret_cast<half*>(qs + (size_t) n_in * n_out);
q8sm60::pack_kernel<<<unsigned((count + 255) / 256), 256>>>(dw, qs, d, count);
const bool took = q8sm60::launch(qs, d, dx, dy, n_in, n_out, ncols, 0);
CK(cudaDeviceSynchronize());
bool ok = true;
if (took) {
std::vector<float> y(ref.size()); CK(cudaMemcpy(y.data(), dy, y.size() * 4, cudaMemcpyDeviceToHost));
double m = 0, e = 0; for (size_t i = 0; i < y.size(); ++i) { m = std::max(m, std::fabs(ref[i])); e = std::max(e, std::fabs(y[i] - ref[i])); }
ok = e / m < 1e-5 && std::isfinite(e);
if (!ok) printf(" FAIL %d -> %d, %d cols: max rel err %.2e\n", n_in, n_out, ncols, e / m);
}
cudaFree(dw); cudaFree(dx); cudaFree(dy); cudaFree(qs);
return ok;
}
int main() {
cudaDeviceProp p; CK(cudaGetDeviceProperties(&p, 0));
printf("%s, %d SMs, %d MHz\n", p.name, p.multiProcessorCount, p.clockRate / 1000);
struct S { const char* name; int n_in, n_out; } shapes[] = {
{"gdn attn_qkv", 2560, 10240}, {"gdn attn_gate", 2560, 6144}, {"ssm_out / attn_output", 6144, 2560},
{"qsa attn_q", 2560, 12288}, {"qsa attn_k / v", 2560, 512}, {"shexp gate / up", 2560, 640},
{"shexp down", 640, 2560}, {"head", 2560, 248320}};
bool ok = true; int checked = 0, declined = 0;
for (const S& s : shapes) for (int c = 1; c <= 8; ++c) {
if (s.n_out > 20000 && c > 2) continue; // the head's CPU reference is slow; 1-2 columns cover its path
if (q8sm60::smem_bytes(c, s.n_in) > q8sm60::MAX_SMEM) { ++declined; continue; }
ok = parity(s.n_in, s.n_out, c) && ok; ++checked;
}
printf("parity: %d shape x column cases %s (%d declined: shared memory)\n\n", checked, ok ? "PASS (max rel err < 1e-5)" : "FAIL", declined);
if (!ok) return 1;
const size_t POOL = 1ull << 30;
int8_t* pool; CK(cudaMalloc(&pool, POOL)); CK(cudaMemset(pool, 1, POOL));
Q81Block* dx; CK(cudaMalloc(&dx, 8 * (6144 / 32) * sizeof(Q81Block))); CK(cudaMemset(dx, 0, 8 * (6144 / 32) * sizeof(Q81Block)));
float* dy; CK(cudaMalloc(&dy, (size_t) 8 * 248320 * 4));
int8_t* head; const size_t head_bytes = (size_t) 248320 * 2560 / 32 * 34; CK(cudaMalloc(&head, head_bytes)); CK(cudaMemset(head, 0, head_bytes));
cudaEvent_t a, b; CK(cudaEventCreate(&a)); CK(cudaEventCreate(&b));
printf("%-22s %6s %7s |", "matrix", "n_in", "n_out"); for (int c = 1; c <= 6; ++c) printf(" T=%d us GB/s", c); printf("\n");
for (const S& s : shapes) {
printf("%-22s %6d %7d |", s.name, s.n_in, s.n_out);
const size_t bytes = (size_t) s.n_in / 32 * 34 * s.n_out;
for (int c = 1; c <= 6; ++c) {
if (q8sm60::smem_bytes(c, s.n_in) > q8sm60::MAX_SMEM) { printf(" %14s", "-"); continue; }
const int iters = s.n_out > 20000 ? 10 : 100;
auto at = [&](int i) -> int8_t* { if (s.n_out > 20000) return head; const size_t span = (POOL - bytes) / 256;
return pool + ((size_t) i * ((bytes + 255) / 256) % span) * 256; };
for (int i = 0; i < 3; ++i) { int8_t* q = at(i); q8sm60::launch(q, (half*) (q + (size_t) s.n_in * s.n_out), dx, dy, s.n_in, s.n_out, c, 0); }
CK(cudaEventRecord(a));
for (int i = 0; i < iters; ++i) { int8_t* q = at(i + 3); q8sm60::launch(q, (half*) (q + (size_t) s.n_in * s.n_out), dx, dy, s.n_in, s.n_out, c, 0); }
CK(cudaEventRecord(b)); CK(cudaEventSynchronize(b));
float ms; CK(cudaEventElapsedTime(&ms, a, b)); const double us = ms * 1000.0 / iters;
printf(" %7.1f %6.0f", us, bytes / (us * 1e3));
}
printf("\n");
}
return 0;
}