Skip to content

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

C++

V100: operator fusions for the decode GEMV / MoE paths, bitwise

ATIVX928d284809fb0ba
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 38c341279..2e74c9540 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -347,6 +347,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
@@ -1013,6 +1014,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})
diff --git a/bench/micro/fusions_parity.cu b/bench/micro/fusions_parity.cu
new file mode 100644
index 000000000..eb4009140
--- /dev/null
+++ b/bench/micro/fusions_parity.cu
@@ -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;
+}
diff --git a/include/strata/kernels/bf16_gemv.hpp b/include/strata/kernels/bf16_gemv.hpp
index f040b04cd..19c4207f3 100644
--- a/include/strata/kernels/bf16_gemv.hpp
+++ b/include/strata/kernels/bf16_gemv.hpp
@@ -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.
diff --git a/include/strata/kernels/quantize_act.hpp b/include/strata/kernels/quantize_act.hpp
index 49d858b25..28f990c36 100644
--- a/include/strata/kernels/quantize_act.hpp
+++ b/include/strata/kernels/quantize_act.hpp
@@ -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);
diff --git a/include/strata/kernels/quantize_act_dev.cuh b/include/strata/kernels/quantize_act_dev.cuh
new file mode 100644
index 000000000..8dc10087f
--- /dev/null
+++ b/include/strata/kernels/quantize_act_dev.cuh
@@ -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
diff --git a/include/strata/kernels/s_gemv.hpp b/include/strata/kernels/s_gemv.hpp
index 340df04e4..d9e22606c 100644
--- a/include/strata/kernels/s_gemv.hpp
+++ b/include/strata/kernels/s_gemv.hpp
@@ -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
diff --git a/include/strata/kernels/s_rowdev.cuh b/include/strata/kernels/s_rowdev.cuh
new file mode 100644
index 000000000..f4f7810c2
--- /dev/null
+++ b/include/strata/kernels/s_rowdev.cuh
@@ -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
diff --git a/include/strata/kernels/swiglu.cuh b/include/strata/kernels/swiglu.cuh
new file mode 100644
index 000000000..1275a9de4
--- /dev/null
+++ b/include/strata/kernels/swiglu.cuh
@@ -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
diff --git a/src/core/layer.cpp b/src/core/layer.cpp
index 1e6b3b930..e26678174 100644
--- a/src/core/layer.cpp
+++ b/src/core/layer.cpp
@@ -101,6 +101,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:
@@ -236,8 +255,12 @@ 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)
+ quantize_act_images(mixed, g.n_embd, b.x_q8_0, b.x_q8k, nullptr, stream); // ONE pass, was two kernels
+#else
quantize_q8_K(mixed, b.x_q8k, g.n_embd, stream);
quantize_q8_0(mixed, b.x_q8_0, g.n_embd, stream);
+#endif
}
st_end(layer, 8, stream);
// ---- 2. qkv = wqkv @ x, with the activation THIS layer's `attn_qkv` asks for
@@ -291,8 +314,13 @@ 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)
+ 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
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);
+#endif
}
if (!fused_pre) try {
if (native_gdn_enabled()) {
@@ -331,8 +359,12 @@ 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)
+ quantize_act_images(b.y, g.ssm_value_dim, b.y_q8_0, b.y_q8k, nullptr, stream); // ONE pass, was two
+#else
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);
+#endif
} 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,
@@ -430,10 +462,18 @@ 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)
+ quantize_act_images(x, g.n_embd, b.x_q8_0, b.x_q8k, b.x_bf16, stream); // ONE pass, was three kernels
+#else
+ 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);
+#endif
+ } 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;
@@ -1043,10 +1083,16 @@ struct Req { const char* suf; }; const WeightRef* w_idxk = v.get("indexer.k_p
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) {
+#if defined(STRATA_EXPERIMENTAL_SM60)
+ 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
+ } else if (!native_bf16_projections) f32_to_bf16_bulk(x, b.x_bf16, g.n_embd, stream);
+#else
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);
+#endif
// ---- 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.
//
@@ -1063,8 +1109,16 @@ 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
+// ---- 3. the indexer's RAW key (and, with the V100 switch, its QUERY in the same kernel; was two launches)
+#if defined(STRATA_EXPERIMENTAL_SM60)
+// 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);
+#else
project_bf16(x, b.x_bf16, (const uint16_t*) w_idxk->data, b.idx_raw, g.n_embd, g.idx_key_dim, false, stream);
+#endif
// ---- 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
@@ -1115,8 +1169,12 @@ 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 !defined(STRATA_EXPERIMENTAL_SM60)
+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);
+#endif
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
diff --git a/src/kernels/cuda/bf16_gemv.cu b/src/kernels/cuda/bf16_gemv.cu
index 04473ad02..a40f6f87a 100644
--- a/src/kernels/cuda/bf16_gemv.cu
+++ b/src/kernels/cuda/bf16_gemv.cu
@@ -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;
diff --git a/src/kernels/cuda/quantize_act.cu b/src/kernels/cuda/quantize_act.cu
index 0e8e03a5a..21cfae733 100644
--- a/src/kernels/cuda/quantize_act.cu
+++ b/src/kernels/cuda/quantize_act.cu
@@ -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
diff --git a/src/kernels/cuda/s2_expert_grouped.cu b/src/kernels/cuda/s2_expert_grouped.cu
index 77bd5d27c..9d5bc1e58 100644
--- a/src/kernels/cuda/s2_expert_grouped.cu
+++ b/src/kernels/cuda/s2_expert_grouped.cu
@@ -161,6 +161,10 @@ __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.
+#if !defined(STRATA_EXPERIMENTAL_SM60)
/// `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`.
///
@@ -173,6 +177,7 @@ __global__ void swiglu_kernel(float* __restrict__ gate_up, long long n_pairs) {
const float u = gate_up[n_pairs + i];
gate_up[i] = (g / (1.0f + __expf(-g))) * u;
}
+#endif
__global__ void swiglu_quantize_q8_0_scaled_kernel(float* __restrict__ gate_up, long long n_pairs,
uint8_t* __restrict__ blocks, float* __restrict__ scales) {
@@ -629,20 +634,27 @@ 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 (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
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);
+#endif
}
- // 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 +742,22 @@ 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 (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
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);
+#endif
}
- 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 +790,18 @@ 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 (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
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);
+#endif
}
- 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 +1195,17 @@ 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 (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
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);
+#endif
}
{
const dim3 grid((unsigned) (H / D_ROWS), (unsigned) cap_groups);
diff --git a/src/kernels/cuda/s_gemv_pair.cu b/src/kernels/cuda/s_gemv_pair.cu
new file mode 100644
index 000000000..7ea8ab937
--- /dev/null
+++ b/src/kernels/cuda/s_gemv_pair.cu
@@ -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
diff --git a/src/kernels/cuda/shared_expert.cu b/src/kernels/cuda/shared_expert.cu
index 450fe24a9..98b634c4d 100644
--- a/src/kernels/cuda/shared_expert.cu
+++ b/src/kernels/cuda/shared_expert.cu
@@ -330,6 +330,87 @@ 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)
+ // 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
// 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 +453,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);
}
}
+#endif
// 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