feat(kernels): legacy S-form GEMVs (s_gemv, split, Q8_K/Q8_0, s2_*) as .cu with planner, summation-order models and host-executed oracle

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Pavlo Ratushnyi
2026-10-14 15:43:17 +02:00
co-authored by Claude Sonnet 5.5
parent 910bd947a2
commit ea64da89c3
9 changed files with 2032 additions and 0 deletions
@@ -0,0 +1,274 @@
// Executes every kernel of s_gemv_legacy.cu (the Original's legacy S-form GEMVs: s_gemv, s_gemv_split, the Q8_K / Q8_0
// activation kernels, s2_gemv, s2_gemv_quads, s2_gemv_q8, s2_gemv_fast) on the host shim and compares each with an FP64
// reference of y[o] = sum_i (cb[code] * scale + offset) * x[i], over S2 / S4 / S8 forms, group sizes 16..64, both
// codebooks, with and without offset, several row-split widths and n_out values that are not multiples of the block.
// * "exact" inputs (powers-of-two scales, small integer activations) make every intermediate exactly representable in
// float, so EVERY summation order must reproduce the reference bit for bit;
// * "random" inputs are checked against a condition-number bound: |y - ref| <= 1e-4 * sum|term|.
// stdout: the golden fixture JSON (inputs and kernel outputs of a few small exact cases) consumed by
// s_gemv_legacy.rs (oracle/fixtures/s_gemv_legacy_golden.json); the PASS/FAIL report goes to stderr.
#include SHIM_KERNEL_0
#include <cstring>
#include <tuple>
#include <string>
struct Rng {
uint64_t s;
uint32_t next() { s = s * 6364136223846793005ULL + 1442695040888963407ULL; return (uint32_t) (s >> 33); }
int range(int lo, int hi) { return lo + (int) (next() % (uint32_t) (hi - lo + 1)); } // inclusive
float unit() { return (float) next() / 2147483648.0f * 2.0f - 1.0f; } // [-1, 1)
};
static const int kTbl[16] = {-127, -104, -83, -65, -49, -35, -22, -10, 1, 13, 25, 38, 53, 69, 89, 113};
static uint16_t to_h(float f) { return __float2half_rn(f).bits; }
static float from_h(uint16_t b) { return __half2float(__ushort_as_half(b)); }
struct Form { int bits, bias, group, codebook, has_offset; };
struct Case {
Form f; long long n_in, n_out;
std::vector<uint8_t> codes; // packed
std::vector<int> raw_codes; // n_out * n_in
std::vector<float> scales, offset;
std::vector<uint16_t> x; // fp16 bits
std::vector<uint8_t> q8k, q80; // block_q8_K (292 B / 256) and block_q8_0 (34 B / 32)
std::vector<double> xf, x8k, x80; // dequantised activations
};
static Case make(Form f, long long n_in, long long n_out, bool exact, uint64_t seed) {
Rng r{seed};
Case c; c.f = f; c.n_in = n_in; c.n_out = n_out;
const int per = 8 / f.bits;
const long long ng = n_in / f.group;
c.raw_codes.resize(n_out * n_in);
c.codes.assign(n_out * n_in / per, 0);
for (long long e = 0; e < n_out * n_in; ++e) {
const int code = (int) (r.next() & ((1u << f.bits) - 1));
c.raw_codes[e] = code;
c.codes[e / per] |= (uint8_t) (code << ((e % per) * f.bits));
}
c.scales.resize(n_out * ng);
c.offset.resize(f.has_offset ? n_out * ng : 0);
static const float sc[3] = {0.25f, 0.5f, 1.0f}, of[5] = {-1.0f, -0.5f, 0.0f, 0.5f, 1.0f};
for (auto& s : c.scales) s = exact ? sc[r.next() % 3] : 0.02f * (1.0f + 0.9f * r.unit());
for (auto& o : c.offset) o = exact ? of[r.next() % 5] : 0.05f * r.unit();
c.x.resize(n_in); c.xf.resize(n_in);
for (long long i = 0; i < n_in; ++i) {
const float v = exact ? (float) r.range(-8, 8) : 1.5f * r.unit();
c.x[i] = to_h(v); c.xf[i] = from_h(c.x[i]);
}
// Q8_K: { f32 d; int8 qs[256]; int16 bsums[16] }
static const float d8[3] = {0.125f, 0.25f, 0.5f};
if (n_in % 256 == 0) {
c.q8k.assign(n_in / 256 * 292, 0); c.x8k.resize(n_in);
for (long long b = 0; b < n_in / 256; ++b) {
const float d = exact ? d8[r.next() % 3] : 0.01f * (1.0f + 0.5f * r.unit());
std::memcpy(&c.q8k[b * 292], &d, 4);
for (int j = 0; j < 256; ++j) {
const int q = exact ? r.range(-15, 15) : r.range(-127, 127);
c.q8k[b * 292 + 4 + j] = (uint8_t) (int8_t) q;
c.x8k[b * 256 + j] = (double) (d * (float) q);
}
}
}
if (n_in % 32 == 0) {
c.q80.assign(n_in / 32 * 34, 0); c.x80.resize(n_in);
for (long long b = 0; b < n_in / 32; ++b) {
const float dv = exact ? d8[r.next() % 3] : 0.01f * (1.0f + 0.5f * r.unit());
const uint16_t dh = to_h(dv);
std::memcpy(&c.q80[b * 34], &dh, 2);
const float d = from_h(dh);
for (int j = 0; j < 32; ++j) {
const int q = exact ? r.range(-15, 15) : r.range(-127, 127);
c.q80[b * 34 + 2 + j] = (uint8_t) (int8_t) q;
c.x80[b * 32 + j] = (double) (d * (float) q);
}
}
}
return c;
}
// FP64 reference and the sum of absolute terms (the error bound's scale) for activation vector `a`.
static void reference(const Case& c, const std::vector<double>& a, std::vector<double>& y, std::vector<double>& mag) {
y.assign(c.n_out, 0.0); mag.assign(c.n_out, 0.0);
const long long ng = c.n_in / c.f.group;
for (long long o = 0; o < c.n_out; ++o)
for (long long i = 0; i < c.n_in; ++i) {
const int code = c.raw_codes[o * c.n_in + i];
const double cb = c.f.codebook ? (double) kTbl[code & 15] : (double) (code + c.f.bias);
const long long g = o * ng + i / c.f.group;
const double w = cb * (double) c.scales[g] + (c.f.has_offset ? (double) c.offset[g] : 0.0);
y[o] += w * a[i];
mag[o] += std::fabs(w * a[i]);
}
}
static int g_fail = 0, g_checks = 0;
static void check(const std::string& what, const Case& c, const std::vector<float>& got, const std::vector<double>& a, bool exact) {
std::vector<double> ref, mag;
reference(c, a, ref, mag);
double worst = 0;
for (long long o = 0; o < c.n_out; ++o) {
const double err = std::fabs((double) got[o] - ref[o]);
const double bound = exact ? 0.0 : 1e-4 * mag[o] + 1e-12;
worst = std::max(worst, mag[o] > 0 ? err / mag[o] : err);
if (err > bound) {
std::fprintf(stderr, "FAIL %s o=%lld got %.9g ref %.9g\n", what.c_str(), o, (double) got[o], ref[o]);
++g_fail;
return;
}
}
++g_checks;
if (getenv("VERBOSE")) std::fprintf(stderr, "ok %s (worst rel-to-magnitude %.2e)\n", what.c_str(), worst);
}
static std::string tag(const Case& c, const char* k, int extra = -1) {
char b[160];
std::snprintf(b, sizeof b, "%s bits=%d bias=%d g=%d cb=%d off=%d n_in=%lld n_out=%lld", k, c.f.bits, c.f.bias, c.f.group, c.f.codebook,
c.f.has_offset, c.n_in, c.n_out);
std::string s = b;
if (extra >= 0) s += " tpr=" + std::to_string(extra);
return s;
}
static int shift_of(int group) { int s = 0; while ((1 << s) < group) ++s; return s; }
static const float* offp(const Case& c) { return c.f.has_offset ? c.offset.data() : nullptr; }
// the entry points differ per width, so the dispatch is spelled out
static std::vector<float> run_s_gemv(const Case& c) {
std::vector<float> y(c.n_out, -1.0f);
shim_launch(dim3((unsigned) ((c.n_out + 127) / 128)), dim3(128), 0, [&] {
auto a = std::make_tuple(c.x.data(), c.codes.data(), c.scales.data(), offp(c), y.data(), c.n_in, c.n_out, c.f.bias, c.f.codebook, c.f.group, c.f.has_offset);
if (c.f.bits == 2) std::apply(leleka_s_gemv_2, a);
else if (c.f.bits == 4) std::apply(leleka_s_gemv_4, a);
else std::apply(leleka_s_gemv_8, a);
});
return y;
}
static std::vector<float> run_split(const Case& c, int tpr) {
std::vector<float> y(c.n_out, -1.0f);
shim_launch(dim3((unsigned) c.n_out), dim3(tpr), (size_t) tpr * 4, [&] {
auto a = std::make_tuple(c.x.data(), c.codes.data(), c.scales.data(), offp(c), y.data(), c.n_in, c.n_out, c.f.bias, c.f.codebook, c.f.group,
shift_of(c.f.group), c.f.has_offset, tpr);
if (c.f.bits == 2) std::apply(leleka_s_gemv_split_2, a);
else if (c.f.bits == 4) std::apply(leleka_s_gemv_split_4, a);
else std::apply(leleka_s_gemv_split_8, a);
});
return y;
}
static std::vector<float> run_q8k(const Case& c) {
std::vector<float> y(c.n_out, -1.0f);
shim_launch(dim3((unsigned) ((c.n_out + 127) / 128)), dim3(128), 0, [&] {
auto a = std::make_tuple(c.q8k.data(), c.codes.data(), c.scales.data(), offp(c), y.data(), c.n_in, c.n_out, c.f.bias, c.f.codebook, c.f.group, c.f.has_offset);
if (c.f.bits == 4) std::apply(leleka_s_gemv_q8k_4, a); else std::apply(leleka_s_gemv_q8k_8, a);
});
return y;
}
static std::vector<float> run_q8_split(const Case& c, bool q8k) {
std::vector<float> y(c.n_out, -1.0f);
shim_launch(dim3((unsigned) ((c.n_out + 7) / 8)), dim3(256), 0, [&] {
auto a = std::make_tuple(q8k ? c.q8k.data() : c.q80.data(), c.codes.data(), c.scales.data(), offp(c), y.data(), c.n_in, c.n_out, c.f.bias,
c.f.codebook, shift_of(c.f.group), c.f.has_offset);
if (q8k) { if (c.f.bits == 4) std::apply(leleka_s_gemv_q8k_split_4, a); else std::apply(leleka_s_gemv_q8k_split_8, a); }
else { if (c.f.bits == 4) std::apply(leleka_s_gemv_q8_0_split_4, a); else std::apply(leleka_s_gemv_q8_0_split_8, a); }
});
return y;
}
static std::vector<float> run_s2(const Case& c, int which, int tpr) { // 0 naive, 1 quads, 2 q8, 3 fast staged, 4 fast unstaged
std::vector<float> y(c.n_out, -1.0f);
if (which == 0) {
shim_launch(dim3((unsigned) ((c.n_out + 127) / 128)), dim3(128), 0, [&] {
leleka_s2_gemv(c.x.data(), c.codes.data(), c.scales.data(), y.data(), c.n_in, c.n_out); });
return y;
}
const size_t smem = (size_t) tpr * 4 + (which == 3 ? 4096 * 2 : 0);
shim_launch(dim3((unsigned) c.n_out), dim3(tpr), smem, [&] {
if (which == 1) leleka_s2_gemv_quads(c.x.data(), c.codes.data(), c.scales.data(), y.data(), c.n_in, c.n_out, tpr);
else if (which == 2) leleka_s2_gemv_q8(c.q80.data(), c.codes.data(), c.scales.data(), y.data(), c.n_in, c.n_out, tpr);
else if (which == 3) leleka_s2_gemv_fast_staged(c.x.data(), c.codes.data(), c.scales.data(), y.data(), c.n_in, c.n_out, tpr);
else leleka_s2_gemv_fast_unstaged(c.x.data(), c.codes.data(), c.scales.data(), y.data(), c.n_in, c.n_out, tpr);
});
return y;
}
static void exercise(Form f, long long n_in, long long n_out, bool exact, uint64_t seed) {
Case c = make(f, n_in, n_out, exact, seed);
check(tag(c, "s_gemv", 0), c, run_s_gemv(c), c.xf, exact);
for (int tpr : {1, 32, 64, 256}) check(tag(c, "s_gemv_split", tpr), c, run_split(c, tpr), c.xf, exact);
if (f.bits != 2 && !c.q8k.empty() && n_in % f.group == 0) {
check(tag(c, "s_gemv_q8k"), c, run_q8k(c), c.x8k, exact);
check(tag(c, "s_gemv_q8k_split"), c, run_q8_split(c, true), c.x8k, exact);
}
if (f.bits != 2 && !c.q80.empty() && f.group % 16 == 0) check(tag(c, "s_gemv_q8_0_split"), c, run_q8_split(c, false), c.x80, exact);
if (f.bits == 2 && f.bias == -1 && f.group == 64 && !f.has_offset && !f.codebook) {
check(tag(c, "s2_gemv"), c, run_s2(c, 0, 0), c.xf, exact);
for (int tpr : {1, 32, 128}) {
check(tag(c, "s2_gemv_quads", tpr), c, run_s2(c, 1, tpr), c.xf, exact);
check(tag(c, "s2_gemv_q8", tpr), c, run_s2(c, 2, tpr), c.x80, exact);
check(tag(c, "s2_gemv_fast_staged", tpr), c, run_s2(c, 3, tpr), c.xf, exact);
check(tag(c, "s2_gemv_fast_unstaged", tpr), c, run_s2(c, 4, tpr), c.xf, exact);
}
}
}
// ---- golden fixture -----------------------------------------------------------------------------------------------
template <typename T> static void emit_array(const char* name, const std::vector<T>& v, bool last = false) {
std::printf("\"%s\":[", name);
for (size_t i = 0; i < v.size(); ++i) {
if constexpr (std::is_floating_point_v<T>) std::printf("%s%.9g", i ? "," : "", (double) v[i]);
else std::printf("%s%lld", i ? "," : "", (long long) v[i]);
}
std::printf("]%s", last ? "" : ",");
}
static bool g_first_case = true;
static void emit_case(const char* name, Form f, long long n_in, long long n_out, uint64_t seed, bool exact = true) {
Case c = make(f, n_in, n_out, exact, seed);
if (!g_first_case) std::printf(",\n");
g_first_case = false;
std::printf("{\"name\":\"%s\",\"exact\":%d,\"bits\":%d,\"bias\":%d,\"group\":%d,\"codebook\":%d,\"has_offset\":%d,\"n_in\":%lld,\"n_out\":%lld,", name, (int) exact, f.bits,
f.bias, f.group, f.codebook, f.has_offset, n_in, n_out);
emit_array("codes", c.codes); emit_array("scales", c.scales); emit_array("offset", c.offset); emit_array("x", c.x);
emit_array("q8k", c.q8k); emit_array("q80", c.q80);
emit_array("y_fp16", run_split(c, 64));
std::vector<float> none;
emit_array("y_q8k", (f.bits != 2 && !c.q8k.empty()) ? run_q8_split(c, true) : none);
emit_array("y_q80", (f.bits != 2) ? run_q8_split(c, false) : run_s2(c, 2, 32), true);
std::printf("}");
}
int main() {
// (bits, bias, group, codebook, has_offset)
const Form forms[] = {
{2, -1, 64, 0, 0}, // S2 (Q2_0)
{2, -2, 32, 0, 1}, // S2 with an offset
{4, -8, 32, 0, 0}, // Q4_0 style
{4, 0, 32, 0, 1}, // Q4_K style (min)
{4, 0, 32, 1, 0}, // IQ4_NL / IQ4_XS codebook
{4, -8, 16, 0, 0},
{8, -16, 32, 0, 1}, // Q5_K style
{8, -128, 32, 0, 0}, // Q8_0
{8, -16, 64, 0, 0},
};
uint64_t seed = 1;
for (const Form& f : forms)
for (long long n_in : {256LL, 768LL})
for (long long n_out : {1LL, 5LL, 13LL})
for (bool exact : {true, false}) exercise(f, n_in, n_out, exact, seed++);
// sizes that exercise the Q8_0 path alone (n_in % 32 == 0 but not % 256) and the tail of the lane stride
for (const Form& f : forms)
for (long long n_in : {64LL, 192LL, 544LL})
if (n_in % f.group == 0) for (bool exact : {true, false}) exercise(f, n_in, 9, exact, seed++);
std::fprintf(stderr, "s_gemv_legacy: %d kernel runs checked, %d failures\n", g_checks, g_fail);
std::fprintf(stderr, g_fail ? "FAIL\n" : "PASS\n");
std::printf("{\"cases\":[\n");
emit_case("s2_g64", forms[0], 128, 3, 9001);
emit_case("s4_iq4nl_g32", forms[4], 256, 3, 9002);
emit_case("s4_k_offset_g32", forms[3], 256, 3, 9003);
emit_case("s8_q5k_g32", forms[6], 256, 3, 9004);
emit_case("s8_q80_g32", forms[7], 64, 3, 9005);
// random (non-exact) inputs: the kernel outputs depend on the summation order, which s_gemv_legacy.rs models
emit_case("s4_iq4nl_random", forms[4], 768, 3, 9006, false);
emit_case("s8_q5k_random", forms[6], 768, 3, 9007, false);
emit_case("s4_k_offset_random", forms[3], 512, 3, 9008, false);
std::printf("\n]}\n");
return g_fail ? 1 : 0;
}
File diff suppressed because one or more lines are too long
@@ -5,3 +5,4 @@ runtime:backend_original_prompt
mmq_original_prefill_misc
device_arena
native_flash_attn
s_gemv_legacy
@@ -21,4 +21,5 @@ run qsa_prompt_attn_variants qsa_prompt_attn_variants.cpp "$src/qsa_prompt_atten
SHIM_CXXFLAGS=-DTEST_V2 run qsa_prompt_attn_v2 qsa_prompt_attn_variants.cpp "$src/qsa_prompt_attention.cu"
run misc_kernels misc_kernels.cpp "$src/mmq_original_prefill_misc.cu" "$src/device_poison.cu" "$src/mmq_original_group_swiglu.cu" > /dev/null
run native_flash_attn flash_attn.cpp "$src/native_flash_attn.cu"
run s_gemv_legacy s_gemv_legacy.cpp "$src/s_gemv_legacy.cu" > /dev/null
exit $failed
@@ -67,6 +67,8 @@ inline float __half2float(__half h) { return h.to_float(); }
inline __half __ushort_as_half(unsigned short v) { __half h; h.bits = v; return h; }
inline __half2 __floats2half2_rn(float a, float b) { return {__float2half_rn(a), __float2half_rn(b)}; }
inline __half2 __halves2half2(__half a, __half b) { return {a, b}; }
inline float __low2float(__half2 h) { return __half2float(h.x); }
inline float __high2float(__half2 h) { return __half2float(h.y); }
inline float2 __half22float2(__half2 h) { return {__half2float(h.x), __half2float(h.y)}; }
inline __half2 __hsub2(__half2 a, __half2 b) {
return {__float2half_rn(__half2float(a.x) - __half2float(b.x)), __float2half_rn(__half2float(a.y) - __half2float(b.y))};
@@ -135,6 +137,9 @@ template <typename T> inline T shim_shfl(T v, int src_of_lane_fn_dummy, int mode
if (mode == 0) { // xor
src = lane ^ arg;
if ((src & ~(width - 1)) != (lane & ~(width - 1))) src = lane;
} else if (mode == 2) { // down: lane + delta, out of the width segment -> own value
src = lane + arg;
if (src >= (lane & ~(width - 1)) + width) src = lane;
} else { // idx
src = (lane & ~(width - 1)) + (arg & (width - 1));
}
@@ -144,6 +149,7 @@ template <typename T> inline T shim_shfl(T v, int src_of_lane_fn_dummy, int mode
}
template <typename T> inline T __shfl_xor_sync(unsigned, T v, int lane_mask, int width = 32) { return shim_shfl(v, 0, 0, lane_mask, width); }
template <typename T> inline T __shfl_sync(unsigned, T v, int src_lane, int width = 32) { return shim_shfl(v, 0, 1, src_lane, width); }
template <typename T> inline T __shfl_down_sync(unsigned, T v, unsigned delta, int width = 32) { return shim_shfl(v, 0, 2, (int) delta, width); }
// ---- launch: grid blocks run one after another, each CUDA thread on its own std::thread
template <typename F>
+1
View File
@@ -83,6 +83,7 @@ pub mod mmq_original_prefill_misc;
pub mod device_arena;
// Pure half of the Original native_flash_attn.cu (admission, geometry, step rule, FP64 specification).
pub mod native_flash_attn;
pub mod s_gemv_legacy;
#[cfg(all(test, feature = "cuda-driver", target_os = "linux", target_pointer_width = "64"))]
mod original_prefill_schedule_crosscheck;
#[cfg(all(
+951
View File
@@ -0,0 +1,951 @@
// Literal Original legacy S-form GEMV kernels (src/kernels/cuda/s_gemv.cu, s2_gemv.cu, s2_gemv_quads.cu, s2_gemv_q8.cu,
// s2_gemv_fast.cu), for the S2/S4/S8 canonical-form packs (docs/pack-format.md: value = cb[code] * scale + offset).
// Everything inside the Original's anonymous namespaces is carried verbatim except:
// * every `__global__` kernel template/function becomes a `__device__ __forceinline__` body of the same name, called by the
// `extern "C" __global__ leleka_*` entries at the end (one entry per template instantiation the host launchers use);
// * `Codebook::Iq4Nl` (s_gemv.hpp) is `kCodebookIq4Nl`; `extern __shared__ float partial[]/smem[]` is a view of `smem_raw`;
// * the S2 files' repeated `QK`/`QK_S2` constants are declared once;
// * `s2_gemv_fast`'s `__constant__ float c_codes[256][4]` was filled by a host `cudaMemcpyToSymbol` (ensure_lut); here it is
// statically initialised with the same values ((byte >> 2k & 3) - 1), generated, so no host step is needed.
// The host launchers (argument checks, geometry, cudaDeviceSynchronize) are not carried: see s_gemv_legacy.rs.
// Original build flags: default (none of these files is in CMakeLists' fast-math list). STATUS: NOT COMPILED OR RUN
// (no nvcc here); executed on the host through oracle/shim (drivers/s_gemv_legacy.cpp).
// Original sources (Strata upstream tree as imported under engine/strata):
// s_gemv.cu sha256 46c946cff34b50f252a5d4a6b2f99e0d30b78a6ad741919417566ccb43017e40
// s2_gemv.cu sha256 4d21a4e14e166b02652719c095b25fa7f346c3d0b3dd1009e050e793b2167b9b
// s2_gemv_quads.cu sha256 3633ad7b7006fdfc96e7b1aa06733168e2292a5b700c49ece60e121c3db4280c
// s2_gemv_q8.cu sha256 c5123b1a7373acad6e62c701bac3ed04f90c1ed5702104008892125de052733d
// s2_gemv_fast.cu sha256 ff3ab5c5b0da5b25aa73f7da3a86894c93960efef3b8c71463d501c1e8adaafe
#include <cuda_fp16.h>
#include <cuda_runtime.h>
#include <cstdint>
enum { kCodebookAffine = 0, kCodebookIq4Nl = 1 };
// `kvalues_iq4nl`: the non-linear codebook, verbatim from ggml-common.h / ggml-quants.c.
//
// **IT WAS IN `__constant__` FOR THE WRONG REASON, AND IT COST 2.12x.** The old comment justified constant
// memory with "every thread reads it and it is the same 16 values for the whole launch". That reasoning is
// exactly backwards: constant memory is fast when the access is UNIFORM - every lane reading the SAME address -
// and a NON-LINEAR codebook means every lane reads a DIFFERENT index, which is the pattern it handles worst.
//
// Measured on `attn_qkv` (IQ4_XS, 10240 x 2560), forcing the Affine codebook so that the memory traffic and the
// instruction count stay identical and only the table read is removed:
//
// codebook probe: IQ4NL 0.2032 ms Affine 0.0960 ms ratio 2.12x
//
// `decode_tbl` below reads a SHARED copy instead: 16 bytes loaded once per block, then an index into shared
// memory that costs at most a four-way bank conflict. The `__constant__` array stays as the source of it.
__constant__ signed char kIq4Nl[16] = {-127, -104, -83, -65, -49, -35, -22, -10,
1, 13, 25, 38, 53, 69, 89, 113};
template <int CODE_BITS>
__device__ __forceinline__ float decode(int code, int bias, int codebook) {
if (codebook == kCodebookIq4Nl) return (float) kIq4Nl[code & 0x0F];
return (float) (code + bias); // the bias is applied to the CODE, in the integer domain
}
/// The same decode with the codebook in SHARED memory, which is what the hot kernels use - see the measurement
/// above. A divergent read of a 16-entry table is the one access pattern constant memory is worst at.
template <int CODE_BITS>
__device__ __forceinline__ float decode_tbl(int code, int bias, int codebook, const signed char* tbl) {
if (codebook == kCodebookIq4Nl) return (float) tbl[code & 0x0F];
return (float) (code + bias);
}
// ---- Q8_K ACTIVATIONS ----------------------------------------------------------------------------------
//
// 292 bytes per 256 elements: `{ f32 d ; int8_t qs[256] ; int16_t bsums[16] }`. `bsums` is not read - it
// exists for ggml's AVX2 dot product - but the STRIDE includes it, so a buffer from `quantize_q8_K` passes
// straight in.
//
// The block's `d` sits at a 4-byte-aligned offset from the buffer base as long as the base is aligned, which
// `cudaMalloc` guarantees.
constexpr int Q8K_BLOCK_BYTES = 292;
constexpr int Q8K_BLOCK_ELEMS = 256;
__device__ __forceinline__ float q8k_at(const uint8_t* __restrict__ x, long long i) {
const uint8_t* blk = x + (i / Q8K_BLOCK_ELEMS) * Q8K_BLOCK_BYTES;
const float d = __ldg((const float*) blk);
const int8_t q = ((const int8_t*) (blk + 4))[i % Q8K_BLOCK_ELEMS];
return d * (float) q;
}
/// **THE Q8_0 ACTIVATION**, which is what the LEGACY block formats want: `block_q8_0` is `{fp16 d; int8 qs[32]}`,
/// 34 bytes per 32 elements, produced by `quantize_q8_0`.
///
/// THE ENGINE HAD NO GEMV FOR THIS, and it was the last activation-contract gap (LEDGER L54). It was described
/// as "Q8_K is not implemented", which is not the situation: `ffn_down_shexp` is IQ4_NL/Q4_0/Q5_0/Q8_0 in EVERY
/// layer, whose `vec_dot_type` is Q8_0 - and its `n_in` is 640, which is not a multiple of 256, so **Q8_K is
/// STRUCTURALLY IMPOSSIBLE for it rather than merely absent**. Every other legacy tensor in the pack is Q2_0,
/// whose attributes happen to be S2's, which is how the S2-only kernel covered them and the hole stayed hidden.
constexpr int Q8_0_BLOCK_BYTES = 34;
constexpr int Q8_0_BLOCK_ELEMS = 32;
__device__ __forceinline__ float q8_0_at(const uint8_t* __restrict__ x, long long i) {
const uint8_t* blk = x + (i / Q8_0_BLOCK_ELEMS) * Q8_0_BLOCK_BYTES;
// a `uint16_t` needs 2-byte alignment and the stride is 34, so every block's `d` is aligned
const float d = __half2float(__ushort_as_half(*(const uint16_t*) blk));
const int8_t q = ((const int8_t*) (blk + 2))[i % Q8_0_BLOCK_ELEMS];
return d * (float) q;
}
/// The Q8_K path, with the SAME weight decode as `s_gemv_kernel` and a different activation loader. The two
/// are separate kernels rather than one templated on the activation kind because the activation POINTER TYPE
/// differs (`uint16_t*` vs `uint8_t*`) and a templated pointer would need a cast at every call site - which is
/// where a wrong stride would hide.
template <int CODE_BITS>
__device__ __forceinline__ void s_gemv_q8k_kernel(const uint8_t* __restrict__ x, const uint8_t* __restrict__ codes,
const float* __restrict__ scales, const float* __restrict__ offset,
float* __restrict__ y, long long n_in, long long n_out, int bias,
int codebook, int group_elems, int has_offset) {
// THE CODEBOOK, IN SHARED MEMORY - 16 bytes, loaded once per block. See the note on `kIq4Nl`.
// THE LOAD AND THE BARRIER COME BEFORE THE EARLY RETURN: `o` is per-THREAD in this kernel, so a thread
// that returned first would leave the others waiting at a barrier it never reaches.
__shared__ signed char s_iq4nl[16];
if (threadIdx.x < 16) s_iq4nl[threadIdx.x] = kIq4Nl[threadIdx.x];
__syncthreads();
const long long o = (long long) blockIdx.x * blockDim.x + threadIdx.x;
if (o >= n_out) return;
constexpr int PER_BYTE = 8 / CODE_BITS;
const long long n_groups = n_in / group_elems;
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 acc = 0.0f;
for (long long g = 0; g < n_groups; ++g) {
const float d = s[g];
const float b = off ? off[g] : 0.0f;
const long long base = g * (long long) group_elems;
for (int j = 0; j < group_elems; ++j) {
const long long i = base + j;
const int code = (c[i / PER_BYTE] >> ((int) (i % PER_BYTE) * CODE_BITS)) & ((1 << CODE_BITS) - 1);
// The offset belongs to the WEIGHT and is applied before the activation multiply - see the note in
// `s_gemv_kernel`, where writing it the other way rounded differently and only the Q4_K case could
// tell.
const float w = decode_tbl<CODE_BITS>(code, bias, codebook, s_iq4nl) * d + b;
acc += w * q8k_at(x, i);
}
}
y[o] = acc;
}
/// One warp per output row, lanes striding the reduction axis: for a fixed `i` consecutive lanes read
/// consecutive activations, which is the coalescing that matters once the output width is small.
///
/// **`group_shift`, NOT `group_elems`, AND IT COSTS A DIVISION PER ELEMENT IF YOU GET IT WRONG.** The
/// sibling fp16 kernel was given this treatment ("a 64-bit integer division on this hardware is a long
/// instruction sequence - one per element, in the hottest loop in the engine") and THIS one was not: it kept
/// `i / group_elems` with `group_elems` a RUNTIME value, once per element, in the kernel that carries most of
/// the model's weight bytes. Every group size the format defines is a power of two, so the divisor is passed
/// as its logarithm and the division becomes a shift; the host refuses a non-power-of-two group rather than
/// computing a wrong index.
/// ONE KERNEL FOR BOTH QUANTIZED ACTIVATIONS, templated on which block format `x` holds. A second copy with a
/// different loader would be a second thing to get wrong, and the only difference IS the loader - the weight
/// decode, the quad loop, the shared codebook and the reduction are identical.
template <int CODE_BITS, bool Q8K>
__device__ __forceinline__ void s_gemv_q8_split_kernel(const uint8_t* __restrict__ x, const uint8_t* __restrict__ codes,
const float* __restrict__ scales, const float* __restrict__ offset,
float* __restrict__ y, long long n_in, long long n_out, int bias,
int codebook, int group_shift, int has_offset) {
constexpr int PER_BYTE = 8 / CODE_BITS;
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;
// THE CODEBOOK, IN SHARED MEMORY. 16 bytes, loaded once per block by the first 16 threads, instead of a
// divergent constant read per element - measured at 2.12x of this whole kernel (see the note on `kIq4Nl`).
//
// THE LOAD AND THE BARRIER COME BEFORE THE EARLY RETURN, as in `s_gemv_q8k_kernel`. The return used to
// sit above them, so whenever `n_out % 8 != 0` the last block's surplus warps left before a barrier the
// others still waited at - undefined behaviour that every shape in the pack (a multiple of 8) happened to
// avoid. `o` is per-WARP, so the return below keeps whole warps together and the shuffle reduction's
// full mask stays valid.
__shared__ signed char s_iq4nl[16];
if (threadIdx.x < 16) s_iq4nl[threadIdx.x] = kIq4Nl[threadIdx.x];
__syncthreads();
if (o >= n_out) return;
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;
// ---- EIGHT CONSECUTIVE ELEMENTS PER LANE, from TWO code loads and ONE scale.
//
// **THIS IS THE EXPERIMENT THE `#pragma unroll` NOTE BELOW LEFT OPEN**, and the note said what it would
// be: "Widening QE to 8 or 16 changes the LOADS THEMSELVES - two or four independent 16-bit words per
// lane - which an unroll cannot do because the extraction code is written for exactly four codes." So a
// lane now takes a double quad: two code words issued before either is consumed, which is what raises the
// bytes in flight. The scale and offset are still ONE load, because eight consecutive elements lie in one
// group whenever `group_elems % 8 == 0` - the launcher asserts that, and every group size this format
// defines (16, 32, 64) satisfies it.
//
// The loop used to take `i = lane, lane+32, ...` - a STRIDE, chosen so consecutive lanes read consecutive
// activations - and paid a code load, a shift-and-mask, and a scale load FOR EVERY ELEMENT. But four
// consecutive elements share one code word (1, 2 or 4 bytes depending on width) and lie in one group,
// because every group size this format defines is a multiple of four. So a lane takes a QUAD:
//
// one code load instead of four
// one scale load instead of four
// one shift per element instead of a divide, a modulo and a shift
//
// THE BIT ORDER IS THE SAME ONE, verified for all three widths: element `i+k` is bits
// `[k*CODE_BITS, (k+1)*CODE_BITS)` of the little-endian word at byte `i/PER_BYTE`, which is what the old
// `(c[e/PER_BYTE] >> ((e%PER_BYTE)*CODE_BITS)) & MASK` computed one element at a time.
//
// THE SUMMATION ORDER CHANGES, which is why `s_gemv_parity` and `s_gemv_q8k_parity` carry tolerances and
// compare against the naive kernel - they are the guard for this, and they are the reason it is safe to do.
constexpr int QE = 16;
// BYTES PER FOUR-CODE WORD, not per octet. The two are easy to confuse and the first version of this
// did: it branched on the octet's total width and so read a uint32 for S4 (whose four codes are a
// uint16) and single bytes for S8 (whose four codes are a uint32). `s_gemv_q8k_parity` failed on
// exactly that, which is what it is for.
constexpr int QW = 4 * CODE_BITS / 8; // 1 for S2, 2 for S4, 4 for S8
constexpr unsigned MASK = (1u << CODE_BITS) - 1u;
long long i = (long long) lane * QE;
// **`#pragma unroll 4` WAS TRIED HERE AND DID NOTHING.** Measured: 184.6 -> 183.9 GB/s at n_out 10240,
// with `s_gemv_parity` and `s_gemv_q8k_parity` both still clean. The hypothesis it was testing is L93 -
// that this kernel's flat ~6 ns per output row is a bytes-in-flight limit, one code load and one scale
// load per lane-iteration with only 20 iterations. A 4x unroll issues four of each before the first is
// consumed, so either the compiler was already doing it or **the limit is not instruction scheduling.**
// Removed rather than kept, because a hint that does not change the timing is a claim that is not true.
//
// What it does NOT rule out is the structural version of the same idea: QE is 4, so a lane consumes ONE
// 2-byte code word per iteration. Widening QE to 8 or 16 changes the LOADS THEMSELVES - two or four
// independent 16-bit words per lane - which an unroll cannot do because the extraction code is written for
// exactly four codes. That is the experiment that would settle it, and it is not this one.
for (; i + QE <= n_in; i += 32 * QE) {
const long long g = i >> group_shift; // the whole octet is in one group: group_elems % 8 == 0
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); }
// ---- THE ACTIVATION BLOCK IS HOISTED OUT OF THE SIXTEEN ELEMENTS, AND THAT WAS THE KERNEL'S COST.
//
// `q8k_at(x, i + k)` computes `(i + k) / 256` and `(i + k) % 256` on EVERY call: a 64-bit integer
// division AND modulo per element, sixteen times per lane-iteration. A 64-bit division on a GPU is a
// software routine of roughly a hundred cycles, and the compiler cannot strength-reduce it because it
// cannot prove `(i + k) / 256 == i / 256` without knowing `i % 256`.
//
// But `QE` is 16, `Q8K_BLOCK_ELEMS` is 256 and `Q8_0_BLOCK_ELEMS` is 32, and the loop advances `i` by
// `32 * QE`. So `i % 256` and `i % 32` are ALWAYS multiples of 16 - which means all QE elements of one
// lane-iteration lie inside ONE block, for either activation kind. One division and one modulo per
// iteration replace sixteen of each, and the sixteen activations become sixteen consecutive int8 loads
// from a pointer computed once.
//
// This is exact, not an approximation: `xi + QE <= blk_elems` holds for every reachable `xi`, so no
// lane-iteration can straddle a block boundary. The tail loop below still uses the accessors because
// its elements do not share a block, and it runs at most once per lane.
const int blk_elems = Q8K ? Q8K_BLOCK_ELEMS : Q8_0_BLOCK_ELEMS;
const uint8_t* xb = x + (i / blk_elems) * (Q8K ? Q8K_BLOCK_BYTES : Q8_0_BLOCK_BYTES);
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_tbl<CODE_BITS>((int) (v & MASK), bias, codebook, s_iq4nl) * d + b;
const float w1 = decode_tbl<CODE_BITS>((int) ((v >> CODE_BITS) & MASK), bias, codebook, s_iq4nl) * d + b;
const float w2 = decode_tbl<CODE_BITS>((int) ((v >> (2 * CODE_BITS)) & MASK), bias, codebook, s_iq4nl) * d + b;
const float w3 = decode_tbl<CODE_BITS>((int) ((v >> (3 * CODE_BITS)) & MASK), bias, codebook, s_iq4nl) * d + b;
const float w4 = decode_tbl<CODE_BITS>((int) (v2 & MASK), bias, codebook, s_iq4nl) * d + b;
const float w5 = decode_tbl<CODE_BITS>((int) ((v2 >> CODE_BITS) & MASK), bias, codebook, s_iq4nl) * d + b;
const float w6 = decode_tbl<CODE_BITS>((int) ((v2 >> (2 * CODE_BITS)) & MASK), bias, codebook, s_iq4nl) * d + b;
const float w7 = decode_tbl<CODE_BITS>((int) ((v2 >> (3 * CODE_BITS)) & MASK), bias, codebook, s_iq4nl) * 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_tbl<CODE_BITS>((int) (v3 & MASK), bias, codebook, s_iq4nl) * d + b;
const float w9 = decode_tbl<CODE_BITS>((int) ((v3 >> CODE_BITS) & MASK), bias, codebook, s_iq4nl) * d + b;
const float w10 = decode_tbl<CODE_BITS>((int) ((v3 >> (2 * CODE_BITS)) & MASK), bias, codebook, s_iq4nl) * d + b;
const float w11 = decode_tbl<CODE_BITS>((int) ((v3 >> (3 * CODE_BITS)) & MASK), bias, codebook, s_iq4nl) * d + b;
const float w12 = decode_tbl<CODE_BITS>((int) (v4 & MASK), bias, codebook, s_iq4nl) * d + b;
const float w13 = decode_tbl<CODE_BITS>((int) ((v4 >> CODE_BITS) & MASK), bias, codebook, s_iq4nl) * d + b;
const float w14 = decode_tbl<CODE_BITS>((int) ((v4 >> (2 * CODE_BITS)) & MASK), bias, codebook, s_iq4nl) * d + b;
const float w15 = decode_tbl<CODE_BITS>((int) ((v4 >> (3 * CODE_BITS)) & MASK), bias, codebook, s_iq4nl) * 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]);
}
// the last, partial quad - at most one per lane
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_tbl<CODE_BITS>(code, bias, codebook, s_iq4nl) * s[g] + (off ? off[g] : 0.0f)) * (Q8K ? q8k_at(x, e) : q8_0_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);
if (lane == 0) y[o] = acc;
}
template <int CODE_BITS>
__device__ __forceinline__ void s_gemv_kernel(const uint16_t* __restrict__ x, const uint8_t* __restrict__ codes,
const float* __restrict__ scales, const float* __restrict__ offset,
float* __restrict__ y, long long n_in, long long n_out, int bias, int codebook,
int group_elems, int has_offset) {
// THE CODEBOOK, IN SHARED MEMORY - 16 bytes, loaded once per block. See the note on `kIq4Nl`.
// THE LOAD AND THE BARRIER COME BEFORE THE EARLY RETURN: `o` is per-THREAD in this kernel, so a thread
// that returned first would leave the others waiting at a barrier it never reaches.
__shared__ signed char s_iq4nl[16];
if (threadIdx.x < 16) s_iq4nl[threadIdx.x] = kIq4Nl[threadIdx.x];
__syncthreads();
const long long o = (long long) blockIdx.x * blockDim.x + threadIdx.x;
if (o >= n_out) return;
constexpr int PER_BYTE = 8 / CODE_BITS;
const long long n_groups = n_in / group_elems;
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 acc = 0.0f;
for (long long g = 0; g < n_groups; ++g) {
const float d = s[g];
const float b = off ? off[g] : 0.0f;
const long long base = g * (long long) group_elems;
for (int j = 0; j < group_elems; ++j) {
const long long i = base + j;
const int code = (c[i / PER_BYTE] >> ((int) (i % PER_BYTE) * CODE_BITS)) & ((1 << CODE_BITS) - 1);
// The offset belongs to the WEIGHT, so it is applied to the decoded value BEFORE the activation
// multiply: `w = code*scale + offset; acc += w * x`. Writing `acc += code*scale*x + offset*x`
// computes a mathematically equal expression that ROUNDS DIFFERENTLY, because it performs two
// multiplications and an addition where this performs one of each. The no-offset types cannot
// tell the difference - which is why this was wrong until the Q4_K case was added.
const float w = decode_tbl<CODE_BITS>(code, bias, codebook, s_iq4nl) * d + b;
acc += w * __half2float(__ushort_as_half(x[i]));
}
}
y[o] = acc;
}
// ---- s_gemv.cu, second anonymous namespace: the row-split fp16 kernel -------------------------------------------
// One BLOCK per output row, `threads_per_row` threads splitting it. Parallelism becomes
// n_out * threads_per_row instead of n_out, which is the whole point: gate/up is [2560 x 640] and 640 threads
// cannot fill 48 SMs.
//
// The reduction is a fixed tree over shared memory rather than atomics, so the result is DETERMINISTIC for a
// given threads_per_row - a race would make the parity test flaky rather than wrong, which is the worst kind
// of failing test.
// NOTE ON `g = e >> group_shift`. The group index was `e / group_elems` with `group_elems` a RUNTIME value,
// and a 64-bit integer division on this hardware is a long instruction sequence - one per element, in the
// hottest loop in the engine. Every group size this format defines is a POWER OF TWO (16, 32, 64), so the
// divisor is passed as its logarithm and the division becomes a shift. The host wrapper refuses a
// non-power-of-two group rather than silently computing a wrong index.
template <int CODE_BITS>
__device__ __forceinline__ void s_gemv_split_kernel(const uint16_t* __restrict__ x, const uint8_t* __restrict__ codes,
const float* __restrict__ scales, const float* __restrict__ offset,
float* __restrict__ y, long long n_in, long long n_out, int bias,
int codebook, int group_elems, int group_shift, int has_offset,
int threads_per_row) {
extern __shared__ __align__(16) unsigned char smem_raw[];
float* partial = reinterpret_cast<float*>(smem_raw);
// THE CODEBOOK, IN SHARED MEMORY - 16 bytes, loaded once per block. See the note on `kIq4Nl`.
// THE LOAD AND THE BARRIER COME BEFORE THE EARLY RETURN: `o` is per-THREAD in this kernel, so a thread
// that returned first would leave the others waiting at a barrier it never reaches.
__shared__ signed char s_iq4nl[16];
if (threadIdx.x < 16) s_iq4nl[threadIdx.x] = kIq4Nl[threadIdx.x];
__syncthreads();
const long long o = blockIdx.x;
if (o >= n_out) return;
const int tid = threadIdx.x;
constexpr int PER_BYTE = 8 / CODE_BITS;
const long long n_groups = n_in / group_elems;
const uint8_t* c = codes + o * (n_in / PER_BYTE);
const float* s = scales + o * n_groups;
const float* off = has_offset ? offset + o * n_groups : nullptr;
// FOUR ACCUMULATORS, NOT ONE. L2 measured this kernel at 0.4% of FP32 peak and 2.1% of bandwidth, so
// neither limit is the constraint - the constraint is the DEPENDENCY CHAIN: a single `acc += ...` serialises
// every FMA behind the previous one's latency (4-6 cycles each, ~1 per 4 cycles achieved), so the SM sits
// idle. Four independent accumulators let the scheduler keep four FMAs in flight, and the loop is
// unrolled by four so the four chains are interleaved. The summation ORDER changes, which is why the
// parity test carries a tolerance and why this kernel's output is checked against the naive one.
// FOUR CONSECUTIVE ELEMENTS PER THREAD, from ONE code load and ONE scale - the same transformation the
// Q8_K kernel got, for the same reason and with the same guard (`s_gemv_parity`). See the long note there
// for the bit order, which is unchanged, and for why the group size is passed as a shift.
//
// THIS KERNEL IS THE ONE `attn_output` AND `shared_expert` USE, so the fix has to exist in both or half the
// model keeps the old instruction count.
constexpr int QE = 4;
constexpr int QB = QE * CODE_BITS / 8; // 1 for S2, 2 for S4, 4 for S8
constexpr unsigned MASK = (1u << CODE_BITS) - 1u;
float acc0 = 0.0f, acc1 = 0.0f, acc2 = 0.0f, acc3 = 0.0f;
long long i = (long long) tid * QE;
for (; i + QE <= n_in; i += (long long) threads_per_row * 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;
if (QB == 1) v = cp[0];
else if (QB == 2) v = *(const uint16_t*) cp;
else v = *(const uint32_t*) cp;
// four halves in ONE 8-byte load; `i` is a multiple of four, so `x + i` is 8-byte aligned
const float2 f01 = __half22float2(*reinterpret_cast<const __half2*>(x + i));
const float2 f23 = __half22float2(*reinterpret_cast<const __half2*>(x + i + 2));
acc0 += (decode_tbl<CODE_BITS>((int) (v & MASK), bias, codebook, s_iq4nl) * d + b) * f01.x;
acc1 += (decode_tbl<CODE_BITS>((int) ((v >> CODE_BITS) & MASK), bias, codebook, s_iq4nl) * d + b) * f01.y;
acc2 += (decode_tbl<CODE_BITS>((int) ((v >> (2 * CODE_BITS)) & MASK), bias, codebook, s_iq4nl) * d + b) * f23.x;
acc3 += (decode_tbl<CODE_BITS>((int) ((v >> (3 * CODE_BITS)) & MASK), bias, codebook, s_iq4nl) * d + b) * f23.y;
}
// the last, partial quad - at most one per thread
for (; i < n_in; i += (long long) threads_per_row * 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_tbl<CODE_BITS>(code, bias, codebook, s_iq4nl) * s[g] + (off ? off[g] : 0.0f)) *
__half2float(__ushort_as_half(x[e]));
}
}
partial[tid] = (acc0 + acc1) + (acc2 + acc3);
__syncthreads();
for (int step = threads_per_row / 2; step > 0; step >>= 1) {
if (tid < step) partial[tid] += partial[tid + step];
__syncthreads();
}
if (tid == 0) y[o] = partial[0];
}
// ---- s2_gemv.cu / s2_gemv_quads.cu / s2_gemv_q8.cu / s2_gemv_fast.cu --------------------------------------------
constexpr int QK = 64;
constexpr int QK_S2 = 64;
constexpr int QK8_0 = 32;
constexpr int MAX_SHARED_HALVES = 4096; // 8 KB of shared for x; n_embd 2560 fits with room
__device__ __forceinline__ void s2_gemv_kernel(const uint16_t* __restrict__ x, const uint8_t* __restrict__ codes,
const float* __restrict__ scales, float* __restrict__ y, long long n_in,
long long n_out) {
const long long o = (long long) blockIdx.x * blockDim.x + threadIdx.x;
if (o >= n_out) return;
const long long nb = n_in / QK;
const uint8_t* c = codes + o * nb * (QK / 4);
const float* s = scales + o * nb;
float acc = 0.0f;
for (long long b = 0; b < nb; ++b) {
const float d = s[b];
const uint8_t* cb = c + b * (QK / 4);
const uint16_t* xb = x + b * QK;
for (int j = 0; j < QK; ++j) {
// (code - 1) in the INTEGER domain, then the group scale, then the activation; the CPU reference
// below is written in the same order so the two differ only by floating-point contraction.
const int code = (cb[j >> 2] >> ((j & 3) * 2)) & 0x03;
acc += (float) (code - 1) * d * __half2float(__ushort_as_half(xb[j]));
}
}
y[o] = acc;
}
__device__ __forceinline__ void s2_gemv_quads_kernel(const uint16_t* __restrict__ x, const uint8_t* __restrict__ codes,
const float* __restrict__ scales, float* __restrict__ y, long long n_in,
long long n_out, int threads_per_row) {
extern __shared__ __align__(16) unsigned char smem_raw[];
float* partial = reinterpret_cast<float*>(smem_raw);
const long long o = blockIdx.x;
if (o >= n_out) return;
const int tid = threadIdx.x;
const long long n_quads = n_in / 4;
const uint8_t* c = codes + o * n_quads; // exactly one code byte per quad
const float* s = scales + o * (n_in / QK_S2);
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]; // ONE load for four codes
const float d = s[q >> 4]; // (q*4) >> 6, the group index as a shift
// ONE 64-bit load for four halves. `x` is 256-byte aligned and four halves are eight bytes, so
// this is an aligned uint2 - if it were not, the misaligned access would fault rather than be slow.
const uint2 xw = *reinterpret_cast<const uint2*>(x + q * 4);
const __half2 h01 = *reinterpret_cast<const __half2*>(&xw.x);
const __half2 h23 = *reinterpret_cast<const __half2*>(&xw.y);
// the four codes, each carrying the -1 bias in the INTEGER domain; the scale is applied once per
// element here rather than once per group, which is the same expression the generic kernel uses
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 * __low2float(h01);
a1 += w1 * __high2float(h01);
a2 += w2 * __low2float(h23);
a3 += w3 * __high2float(h23);
}
partial[tid] = (a0 + a1) + (a2 + a3);
__syncthreads();
for (int step = threads_per_row / 2; step > 0; step >>= 1) {
if (tid < step) partial[tid] += partial[tid + step];
__syncthreads();
}
if (tid == 0) y[o] = partial[0];
}
__device__ __forceinline__ void s2_gemv_q8_kernel(const uint8_t* __restrict__ act, const uint8_t* __restrict__ codes,
const float* __restrict__ scales, float* __restrict__ y, long long n_in,
long long n_out, int threads_per_row) {
extern __shared__ __align__(16) unsigned char smem_raw[];
float* partial = reinterpret_cast<float*>(smem_raw);
const long long o = blockIdx.x;
if (o >= n_out) return;
const int tid = threadIdx.x;
const long long n_quads = n_in / 4;
const uint8_t* c = codes + o * n_quads; // one code byte per quad
const float* s = scales + o * (n_in / QK_S2);
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]; // (q*4) >> 6, the S2 group index as a shift
// the activation quad: four int8 in one 32-element block, so one block scale
const long long ablk = (q * 4) / QK8_0;
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 = reinterpret_cast<const int8_t*>(blk + 2);
const int off = (int) ((q * 4) % QK8_0);
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);
__syncthreads();
for (int step = threads_per_row / 2; step > 0; step >>= 1) {
if (tid < step) partial[tid] += partial[tid + step];
__syncthreads();
}
if (tid == 0) y[o] = partial[0];
}
// byte -> the four code values with the -1 bias already applied, in element order (bits 0,2,4,6). Generated.
__constant__ float c_codes[256][4] = {
{-1.0f, -1.0f, -1.0f, -1.0f},
{0.0f, -1.0f, -1.0f, -1.0f},
{1.0f, -1.0f, -1.0f, -1.0f},
{2.0f, -1.0f, -1.0f, -1.0f},
{-1.0f, 0.0f, -1.0f, -1.0f},
{0.0f, 0.0f, -1.0f, -1.0f},
{1.0f, 0.0f, -1.0f, -1.0f},
{2.0f, 0.0f, -1.0f, -1.0f},
{-1.0f, 1.0f, -1.0f, -1.0f},
{0.0f, 1.0f, -1.0f, -1.0f},
{1.0f, 1.0f, -1.0f, -1.0f},
{2.0f, 1.0f, -1.0f, -1.0f},
{-1.0f, 2.0f, -1.0f, -1.0f},
{0.0f, 2.0f, -1.0f, -1.0f},
{1.0f, 2.0f, -1.0f, -1.0f},
{2.0f, 2.0f, -1.0f, -1.0f},
{-1.0f, -1.0f, 0.0f, -1.0f},
{0.0f, -1.0f, 0.0f, -1.0f},
{1.0f, -1.0f, 0.0f, -1.0f},
{2.0f, -1.0f, 0.0f, -1.0f},
{-1.0f, 0.0f, 0.0f, -1.0f},
{0.0f, 0.0f, 0.0f, -1.0f},
{1.0f, 0.0f, 0.0f, -1.0f},
{2.0f, 0.0f, 0.0f, -1.0f},
{-1.0f, 1.0f, 0.0f, -1.0f},
{0.0f, 1.0f, 0.0f, -1.0f},
{1.0f, 1.0f, 0.0f, -1.0f},
{2.0f, 1.0f, 0.0f, -1.0f},
{-1.0f, 2.0f, 0.0f, -1.0f},
{0.0f, 2.0f, 0.0f, -1.0f},
{1.0f, 2.0f, 0.0f, -1.0f},
{2.0f, 2.0f, 0.0f, -1.0f},
{-1.0f, -1.0f, 1.0f, -1.0f},
{0.0f, -1.0f, 1.0f, -1.0f},
{1.0f, -1.0f, 1.0f, -1.0f},
{2.0f, -1.0f, 1.0f, -1.0f},
{-1.0f, 0.0f, 1.0f, -1.0f},
{0.0f, 0.0f, 1.0f, -1.0f},
{1.0f, 0.0f, 1.0f, -1.0f},
{2.0f, 0.0f, 1.0f, -1.0f},
{-1.0f, 1.0f, 1.0f, -1.0f},
{0.0f, 1.0f, 1.0f, -1.0f},
{1.0f, 1.0f, 1.0f, -1.0f},
{2.0f, 1.0f, 1.0f, -1.0f},
{-1.0f, 2.0f, 1.0f, -1.0f},
{0.0f, 2.0f, 1.0f, -1.0f},
{1.0f, 2.0f, 1.0f, -1.0f},
{2.0f, 2.0f, 1.0f, -1.0f},
{-1.0f, -1.0f, 2.0f, -1.0f},
{0.0f, -1.0f, 2.0f, -1.0f},
{1.0f, -1.0f, 2.0f, -1.0f},
{2.0f, -1.0f, 2.0f, -1.0f},
{-1.0f, 0.0f, 2.0f, -1.0f},
{0.0f, 0.0f, 2.0f, -1.0f},
{1.0f, 0.0f, 2.0f, -1.0f},
{2.0f, 0.0f, 2.0f, -1.0f},
{-1.0f, 1.0f, 2.0f, -1.0f},
{0.0f, 1.0f, 2.0f, -1.0f},
{1.0f, 1.0f, 2.0f, -1.0f},
{2.0f, 1.0f, 2.0f, -1.0f},
{-1.0f, 2.0f, 2.0f, -1.0f},
{0.0f, 2.0f, 2.0f, -1.0f},
{1.0f, 2.0f, 2.0f, -1.0f},
{2.0f, 2.0f, 2.0f, -1.0f},
{-1.0f, -1.0f, -1.0f, 0.0f},
{0.0f, -1.0f, -1.0f, 0.0f},
{1.0f, -1.0f, -1.0f, 0.0f},
{2.0f, -1.0f, -1.0f, 0.0f},
{-1.0f, 0.0f, -1.0f, 0.0f},
{0.0f, 0.0f, -1.0f, 0.0f},
{1.0f, 0.0f, -1.0f, 0.0f},
{2.0f, 0.0f, -1.0f, 0.0f},
{-1.0f, 1.0f, -1.0f, 0.0f},
{0.0f, 1.0f, -1.0f, 0.0f},
{1.0f, 1.0f, -1.0f, 0.0f},
{2.0f, 1.0f, -1.0f, 0.0f},
{-1.0f, 2.0f, -1.0f, 0.0f},
{0.0f, 2.0f, -1.0f, 0.0f},
{1.0f, 2.0f, -1.0f, 0.0f},
{2.0f, 2.0f, -1.0f, 0.0f},
{-1.0f, -1.0f, 0.0f, 0.0f},
{0.0f, -1.0f, 0.0f, 0.0f},
{1.0f, -1.0f, 0.0f, 0.0f},
{2.0f, -1.0f, 0.0f, 0.0f},
{-1.0f, 0.0f, 0.0f, 0.0f},
{0.0f, 0.0f, 0.0f, 0.0f},
{1.0f, 0.0f, 0.0f, 0.0f},
{2.0f, 0.0f, 0.0f, 0.0f},
{-1.0f, 1.0f, 0.0f, 0.0f},
{0.0f, 1.0f, 0.0f, 0.0f},
{1.0f, 1.0f, 0.0f, 0.0f},
{2.0f, 1.0f, 0.0f, 0.0f},
{-1.0f, 2.0f, 0.0f, 0.0f},
{0.0f, 2.0f, 0.0f, 0.0f},
{1.0f, 2.0f, 0.0f, 0.0f},
{2.0f, 2.0f, 0.0f, 0.0f},
{-1.0f, -1.0f, 1.0f, 0.0f},
{0.0f, -1.0f, 1.0f, 0.0f},
{1.0f, -1.0f, 1.0f, 0.0f},
{2.0f, -1.0f, 1.0f, 0.0f},
{-1.0f, 0.0f, 1.0f, 0.0f},
{0.0f, 0.0f, 1.0f, 0.0f},
{1.0f, 0.0f, 1.0f, 0.0f},
{2.0f, 0.0f, 1.0f, 0.0f},
{-1.0f, 1.0f, 1.0f, 0.0f},
{0.0f, 1.0f, 1.0f, 0.0f},
{1.0f, 1.0f, 1.0f, 0.0f},
{2.0f, 1.0f, 1.0f, 0.0f},
{-1.0f, 2.0f, 1.0f, 0.0f},
{0.0f, 2.0f, 1.0f, 0.0f},
{1.0f, 2.0f, 1.0f, 0.0f},
{2.0f, 2.0f, 1.0f, 0.0f},
{-1.0f, -1.0f, 2.0f, 0.0f},
{0.0f, -1.0f, 2.0f, 0.0f},
{1.0f, -1.0f, 2.0f, 0.0f},
{2.0f, -1.0f, 2.0f, 0.0f},
{-1.0f, 0.0f, 2.0f, 0.0f},
{0.0f, 0.0f, 2.0f, 0.0f},
{1.0f, 0.0f, 2.0f, 0.0f},
{2.0f, 0.0f, 2.0f, 0.0f},
{-1.0f, 1.0f, 2.0f, 0.0f},
{0.0f, 1.0f, 2.0f, 0.0f},
{1.0f, 1.0f, 2.0f, 0.0f},
{2.0f, 1.0f, 2.0f, 0.0f},
{-1.0f, 2.0f, 2.0f, 0.0f},
{0.0f, 2.0f, 2.0f, 0.0f},
{1.0f, 2.0f, 2.0f, 0.0f},
{2.0f, 2.0f, 2.0f, 0.0f},
{-1.0f, -1.0f, -1.0f, 1.0f},
{0.0f, -1.0f, -1.0f, 1.0f},
{1.0f, -1.0f, -1.0f, 1.0f},
{2.0f, -1.0f, -1.0f, 1.0f},
{-1.0f, 0.0f, -1.0f, 1.0f},
{0.0f, 0.0f, -1.0f, 1.0f},
{1.0f, 0.0f, -1.0f, 1.0f},
{2.0f, 0.0f, -1.0f, 1.0f},
{-1.0f, 1.0f, -1.0f, 1.0f},
{0.0f, 1.0f, -1.0f, 1.0f},
{1.0f, 1.0f, -1.0f, 1.0f},
{2.0f, 1.0f, -1.0f, 1.0f},
{-1.0f, 2.0f, -1.0f, 1.0f},
{0.0f, 2.0f, -1.0f, 1.0f},
{1.0f, 2.0f, -1.0f, 1.0f},
{2.0f, 2.0f, -1.0f, 1.0f},
{-1.0f, -1.0f, 0.0f, 1.0f},
{0.0f, -1.0f, 0.0f, 1.0f},
{1.0f, -1.0f, 0.0f, 1.0f},
{2.0f, -1.0f, 0.0f, 1.0f},
{-1.0f, 0.0f, 0.0f, 1.0f},
{0.0f, 0.0f, 0.0f, 1.0f},
{1.0f, 0.0f, 0.0f, 1.0f},
{2.0f, 0.0f, 0.0f, 1.0f},
{-1.0f, 1.0f, 0.0f, 1.0f},
{0.0f, 1.0f, 0.0f, 1.0f},
{1.0f, 1.0f, 0.0f, 1.0f},
{2.0f, 1.0f, 0.0f, 1.0f},
{-1.0f, 2.0f, 0.0f, 1.0f},
{0.0f, 2.0f, 0.0f, 1.0f},
{1.0f, 2.0f, 0.0f, 1.0f},
{2.0f, 2.0f, 0.0f, 1.0f},
{-1.0f, -1.0f, 1.0f, 1.0f},
{0.0f, -1.0f, 1.0f, 1.0f},
{1.0f, -1.0f, 1.0f, 1.0f},
{2.0f, -1.0f, 1.0f, 1.0f},
{-1.0f, 0.0f, 1.0f, 1.0f},
{0.0f, 0.0f, 1.0f, 1.0f},
{1.0f, 0.0f, 1.0f, 1.0f},
{2.0f, 0.0f, 1.0f, 1.0f},
{-1.0f, 1.0f, 1.0f, 1.0f},
{0.0f, 1.0f, 1.0f, 1.0f},
{1.0f, 1.0f, 1.0f, 1.0f},
{2.0f, 1.0f, 1.0f, 1.0f},
{-1.0f, 2.0f, 1.0f, 1.0f},
{0.0f, 2.0f, 1.0f, 1.0f},
{1.0f, 2.0f, 1.0f, 1.0f},
{2.0f, 2.0f, 1.0f, 1.0f},
{-1.0f, -1.0f, 2.0f, 1.0f},
{0.0f, -1.0f, 2.0f, 1.0f},
{1.0f, -1.0f, 2.0f, 1.0f},
{2.0f, -1.0f, 2.0f, 1.0f},
{-1.0f, 0.0f, 2.0f, 1.0f},
{0.0f, 0.0f, 2.0f, 1.0f},
{1.0f, 0.0f, 2.0f, 1.0f},
{2.0f, 0.0f, 2.0f, 1.0f},
{-1.0f, 1.0f, 2.0f, 1.0f},
{0.0f, 1.0f, 2.0f, 1.0f},
{1.0f, 1.0f, 2.0f, 1.0f},
{2.0f, 1.0f, 2.0f, 1.0f},
{-1.0f, 2.0f, 2.0f, 1.0f},
{0.0f, 2.0f, 2.0f, 1.0f},
{1.0f, 2.0f, 2.0f, 1.0f},
{2.0f, 2.0f, 2.0f, 1.0f},
{-1.0f, -1.0f, -1.0f, 2.0f},
{0.0f, -1.0f, -1.0f, 2.0f},
{1.0f, -1.0f, -1.0f, 2.0f},
{2.0f, -1.0f, -1.0f, 2.0f},
{-1.0f, 0.0f, -1.0f, 2.0f},
{0.0f, 0.0f, -1.0f, 2.0f},
{1.0f, 0.0f, -1.0f, 2.0f},
{2.0f, 0.0f, -1.0f, 2.0f},
{-1.0f, 1.0f, -1.0f, 2.0f},
{0.0f, 1.0f, -1.0f, 2.0f},
{1.0f, 1.0f, -1.0f, 2.0f},
{2.0f, 1.0f, -1.0f, 2.0f},
{-1.0f, 2.0f, -1.0f, 2.0f},
{0.0f, 2.0f, -1.0f, 2.0f},
{1.0f, 2.0f, -1.0f, 2.0f},
{2.0f, 2.0f, -1.0f, 2.0f},
{-1.0f, -1.0f, 0.0f, 2.0f},
{0.0f, -1.0f, 0.0f, 2.0f},
{1.0f, -1.0f, 0.0f, 2.0f},
{2.0f, -1.0f, 0.0f, 2.0f},
{-1.0f, 0.0f, 0.0f, 2.0f},
{0.0f, 0.0f, 0.0f, 2.0f},
{1.0f, 0.0f, 0.0f, 2.0f},
{2.0f, 0.0f, 0.0f, 2.0f},
{-1.0f, 1.0f, 0.0f, 2.0f},
{0.0f, 1.0f, 0.0f, 2.0f},
{1.0f, 1.0f, 0.0f, 2.0f},
{2.0f, 1.0f, 0.0f, 2.0f},
{-1.0f, 2.0f, 0.0f, 2.0f},
{0.0f, 2.0f, 0.0f, 2.0f},
{1.0f, 2.0f, 0.0f, 2.0f},
{2.0f, 2.0f, 0.0f, 2.0f},
{-1.0f, -1.0f, 1.0f, 2.0f},
{0.0f, -1.0f, 1.0f, 2.0f},
{1.0f, -1.0f, 1.0f, 2.0f},
{2.0f, -1.0f, 1.0f, 2.0f},
{-1.0f, 0.0f, 1.0f, 2.0f},
{0.0f, 0.0f, 1.0f, 2.0f},
{1.0f, 0.0f, 1.0f, 2.0f},
{2.0f, 0.0f, 1.0f, 2.0f},
{-1.0f, 1.0f, 1.0f, 2.0f},
{0.0f, 1.0f, 1.0f, 2.0f},
{1.0f, 1.0f, 1.0f, 2.0f},
{2.0f, 1.0f, 1.0f, 2.0f},
{-1.0f, 2.0f, 1.0f, 2.0f},
{0.0f, 2.0f, 1.0f, 2.0f},
{1.0f, 2.0f, 1.0f, 2.0f},
{2.0f, 2.0f, 1.0f, 2.0f},
{-1.0f, -1.0f, 2.0f, 2.0f},
{0.0f, -1.0f, 2.0f, 2.0f},
{1.0f, -1.0f, 2.0f, 2.0f},
{2.0f, -1.0f, 2.0f, 2.0f},
{-1.0f, 0.0f, 2.0f, 2.0f},
{0.0f, 0.0f, 2.0f, 2.0f},
{1.0f, 0.0f, 2.0f, 2.0f},
{2.0f, 0.0f, 2.0f, 2.0f},
{-1.0f, 1.0f, 2.0f, 2.0f},
{0.0f, 1.0f, 2.0f, 2.0f},
{1.0f, 1.0f, 2.0f, 2.0f},
{2.0f, 1.0f, 2.0f, 2.0f},
{-1.0f, 2.0f, 2.0f, 2.0f},
{0.0f, 2.0f, 2.0f, 2.0f},
{1.0f, 2.0f, 2.0f, 2.0f},
{2.0f, 2.0f, 2.0f, 2.0f}
};
// One block per output row. `staged` says whether x was copied to shared, so the SAME kernel covers both
// configurations and the bench can measure them against each other with nothing else changed.
template <bool STAGE_X>
__device__ __forceinline__ void s2_gemv_fast_kernel(const uint16_t* __restrict__ x, const uint8_t* __restrict__ codes,
const float* __restrict__ scales, float* __restrict__ y, long long n_in,
long long n_out, int threads_per_row) {
extern __shared__ __align__(16) unsigned char smem_raw[];
float* smem = reinterpret_cast<float*>(smem_raw);
__half* sx = reinterpret_cast<__half*>(smem); // [threads_per_row, ...] partials live after
float* partial = smem + (STAGE_X ? (MAX_SHARED_HALVES / 2) : 0);
const long long o = blockIdx.x;
if (o >= n_out) return;
const int tid = threadIdx.x;
if (STAGE_X) {
const __half* xh = reinterpret_cast<const __half*>(x);
for (long long i = tid; i < n_in; i += threads_per_row) sx[i] = xh[i];
__syncthreads();
}
const long long n_quads = n_in / 4;
const uint8_t* c = codes + o * n_quads;
const float* s = scales + o * (n_in / QK_S2);
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]; // ONE load for four codes
const float d = s[q >> 4]; // (q*4) >> 6
const float4 cv = *reinterpret_cast<const float4*>(&c_codes[byte][0]); // one broadcast load
if (STAGE_X) {
const __half2 h01 = *reinterpret_cast<const __half2*>(&sx[q * 4]);
const __half2 h23 = *reinterpret_cast<const __half2*>(&sx[q * 4 + 2]);
a0 += cv.x * d * __low2float(h01);
a1 += cv.y * d * __high2float(h01);
a2 += cv.z * d * __low2float(h23);
a3 += cv.w * d * __high2float(h23);
} else {
const uint2 xw2 = *reinterpret_cast<const uint2*>(x + q * 4);
const __half2 h01 = *reinterpret_cast<const __half2*>(&xw2.x);
const __half2 h23 = *reinterpret_cast<const __half2*>(&xw2.y);
a0 += cv.x * d * __low2float(h01);
a1 += cv.y * d * __high2float(h01);
a2 += cv.z * d * __low2float(h23);
a3 += cv.w * d * __high2float(h23);
}
}
partial[tid] = (a0 + a1) + (a2 + a3);
__syncthreads();
for (int step = threads_per_row / 2; step > 0; step >>= 1) {
if (tid < step) partial[tid] += partial[tid + step];
__syncthreads();
}
if (tid == 0) y[o] = partial[0];
}
// ---- entries -----------------------------------------------------------------------------------------------------
// Argument order is the Original kernel's. Launch geometry (see s_gemv_legacy.rs):
// leleka_s_gemv_*, leleka_s_gemv_q8k_* : 128 threads, ceil(n_out / 128) blocks, no dynamic shared
// leleka_s_gemv_split_* : threads_per_row threads, n_out blocks, threads_per_row * 4 B dynamic shared
// leleka_s_gemv_q8k_split_* / q8_0_split_* : 256 threads (8 warps), ceil(n_out / 8) blocks, no dynamic shared
// leleka_s2_gemv : 128 threads, ceil(n_out / 128) blocks
// leleka_s2_gemv_quads / _q8 : threads_per_row threads, n_out blocks, threads_per_row * 4 B dynamic shared
// leleka_s2_gemv_fast_{staged,unstaged} : threads_per_row threads, n_out blocks, [8192 B +] threads_per_row * 4 B dynamic shared
#define LELEKA_S_FP16_ARGS const uint16_t* __restrict__ x, const uint8_t* __restrict__ codes, const float* __restrict__ scales, \
const float* __restrict__ offset, float* __restrict__ y, long long n_in, long long n_out, int bias, int codebook, int group_elems, \
int has_offset
#define LELEKA_S_Q8_ARGS const uint8_t* __restrict__ x, const uint8_t* __restrict__ codes, const float* __restrict__ scales, \
const float* __restrict__ offset, float* __restrict__ y, long long n_in, long long n_out, int bias, int codebook, int group_shift, \
int has_offset
#define LELEKA_S_GEMV(B) extern "C" __global__ void leleka_s_gemv_##B(LELEKA_S_FP16_ARGS) { \
s_gemv_kernel<B>(x, codes, scales, offset, y, n_in, n_out, bias, codebook, group_elems, has_offset); }
LELEKA_S_GEMV(2)
LELEKA_S_GEMV(4)
LELEKA_S_GEMV(8)
#define LELEKA_S_GEMV_SPLIT(B) extern "C" __global__ void leleka_s_gemv_split_##B( \
const uint16_t* __restrict__ x, const uint8_t* __restrict__ codes, const float* __restrict__ scales, \
const float* __restrict__ offset, float* __restrict__ y, long long n_in, long long n_out, int bias, int codebook, \
int group_elems, int group_shift, int has_offset, int threads_per_row) { \
s_gemv_split_kernel<B>(x, codes, scales, offset, y, n_in, n_out, bias, codebook, group_elems, group_shift, has_offset, \
threads_per_row); }
LELEKA_S_GEMV_SPLIT(2)
LELEKA_S_GEMV_SPLIT(4)
LELEKA_S_GEMV_SPLIT(8)
// Q8_K activation, thread-per-row kernel (s_gemv_q8k)
#define LELEKA_S_GEMV_Q8K(B) extern "C" __global__ void leleka_s_gemv_q8k_##B( \
const uint8_t* __restrict__ x, const uint8_t* __restrict__ codes, const float* __restrict__ scales, \
const float* __restrict__ offset, float* __restrict__ y, long long n_in, long long n_out, int bias, int codebook, \
int group_elems, int has_offset) { \
s_gemv_q8k_kernel<B>(x, codes, scales, offset, y, n_in, n_out, bias, codebook, group_elems, has_offset); }
LELEKA_S_GEMV_Q8K(4)
LELEKA_S_GEMV_Q8K(8)
// warp-per-row kernels: Q8_K (s_gemv_q8k_split) and Q8_0 (s_gemv_q8_0_split) activations
#define LELEKA_S_GEMV_Q8_SPLIT(NAME, B, IS_Q8K) extern "C" __global__ void NAME(LELEKA_S_Q8_ARGS) { \
s_gemv_q8_split_kernel<B, IS_Q8K>(x, codes, scales, offset, y, n_in, n_out, bias, codebook, group_shift, has_offset); }
LELEKA_S_GEMV_Q8_SPLIT(leleka_s_gemv_q8k_split_4, 4, true)
LELEKA_S_GEMV_Q8_SPLIT(leleka_s_gemv_q8k_split_8, 8, true)
LELEKA_S_GEMV_Q8_SPLIT(leleka_s_gemv_q8_0_split_4, 4, false)
LELEKA_S_GEMV_Q8_SPLIT(leleka_s_gemv_q8_0_split_8, 8, false)
extern "C" __global__ void leleka_s2_gemv(const uint16_t* __restrict__ x, const uint8_t* __restrict__ codes,
const float* __restrict__ scales, float* __restrict__ y, long long n_in,
long long n_out) {
s2_gemv_kernel(x, codes, scales, y, n_in, n_out);
}
extern "C" __global__ void leleka_s2_gemv_quads(const uint16_t* __restrict__ x, const uint8_t* __restrict__ codes,
const float* __restrict__ scales, float* __restrict__ y, long long n_in,
long long n_out, int threads_per_row) {
s2_gemv_quads_kernel(x, codes, scales, y, n_in, n_out, threads_per_row);
}
extern "C" __global__ void leleka_s2_gemv_q8(const uint8_t* __restrict__ act, const uint8_t* __restrict__ codes,
const float* __restrict__ scales, float* __restrict__ y, long long n_in,
long long n_out, int threads_per_row) {
s2_gemv_q8_kernel(act, codes, scales, y, n_in, n_out, threads_per_row);
}
extern "C" __global__ void leleka_s2_gemv_fast_staged(const uint16_t* __restrict__ x, const uint8_t* __restrict__ codes,
const float* __restrict__ scales, float* __restrict__ y,
long long n_in, long long n_out, int threads_per_row) {
s2_gemv_fast_kernel<true>(x, codes, scales, y, n_in, n_out, threads_per_row);
}
extern "C" __global__ void leleka_s2_gemv_fast_unstaged(const uint16_t* __restrict__ x, const uint8_t* __restrict__ codes,
const float* __restrict__ scales, float* __restrict__ y,
long long n_in, long long n_out, int threads_per_row) {
s2_gemv_fast_kernel<false>(x, codes, scales, y, n_in, n_out, threads_per_row);
}
Binary file not shown.
+788
View File
@@ -0,0 +1,788 @@
//! Pure half of the Original legacy S-form GEMV kernels (`s_gemv.cu`, `s2_gemv.cu`, `s2_gemv_quads.cu`, `s2_gemv_q8.cu`,
//! `s2_gemv_fast.cu`): the host launchers' admission rules and launch geometry, and CPU models of the kernels' summation
//! order. CUDA source: `s_gemv_legacy.cu`, executed on the host shim by `oracle/drivers/s_gemv_legacy.cpp` against an FP64
//! reference; the golden fixture `oracle/fixtures/s_gemv_legacy_golden.json` (inputs and shim-kernel outputs) is checked
//! bit-exactly by the models here.
//!
//! Canonical S-form (docs/pack-format.md): `value = cb[code] * scale + offset`, `y[o] = sum_i value[o][i] * x[i]`; a
//! tensor is `[n_in, n_out]` with `n_in` contiguous, row `o` holds `n_in / (8 / bits)` code bytes and `n_in / group`
//! scales (and offsets when the form has them). Activations are fp16, `block_q8_K` (292 B / 256 elements) or `block_q8_0`
//! (34 B / 32 elements).
//!
//! No Rust GPU owner launches these yet (they are the legacy path: the production S-form packs go through the MMQ/native
//! kernels). The planners below are what such an owner calls before `Module::launch`; each returns `Err` where the Original
//! launcher printed to stderr and called `std::exit(1)`, and `Ok(None)` where it returned early (`n_in <= 0 || n_out <= 0`).
//!
//! Checks stricter than the Original (all fail-closed, none changes a result the Original would have computed correctly):
//! the split/quads/q8/fast launchers also require a power-of-two `threads_per_row` in `1..=1024` (the in-kernel tree
//! reduction silently drops partial sums otherwise), and `s_gemv_split` also requires `n_in % group_elems == 0` and an
//! offset pointer when the form has one (the Original checked these only in `s_gemv`).
pub const IQ4NL: [i8; 16] = [-127, -104, -83, -65, -49, -35, -22, -10, 1, 13, 25, 38, 53, 69, 89, 113];
pub const Q8K_BLOCK_BYTES: usize = 292;
pub const Q8K_BLOCK_ELEMS: usize = 256;
pub const Q8_0_BLOCK_BYTES: usize = 34;
pub const Q8_0_BLOCK_ELEMS: usize = 32;
pub const S2_QK: i64 = 64;
/// `MAX_SHARED_HALVES` of `s2_gemv_fast.cu`: halves of `x` the staged variant keeps in shared memory.
pub const S2_FAST_MAX_SHARED_HALVES: i64 = 4096;
/// Original build flags (none of these files is in CMakeLists' fast-math list).
pub const NVCC_FLAGS: &[&str] = &["-ptx", "-O3", "-arch=sm_120"];
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Codebook {
/// `code + bias`, the bias applied in the integer domain.
Affine = 0,
/// The non-linear `kvalues_iq4nl` table, indexed by the low 4 bits.
Iq4Nl = 1,
}
/// `SForm` of s_gemv.hpp.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct SForm {
pub code_bits: i32,
pub code_bias: i32,
pub group_elems: i32,
pub codebook: Codebook,
pub has_offset: bool,
/// 0 = Q8_0, 1 = Q8_K (`vec_dot_type`); carried, never derived.
pub act_kind: i32,
}
impl Default for SForm {
fn default() -> Self {
Self { code_bits: 2, code_bias: -1, group_elems: 64, codebook: Codebook::Affine, has_offset: false, act_kind: 0 }
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Launch {
pub grid: [u32; 3],
pub block: [u32; 3],
pub dynamic_shared: u32,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Kernel {
SGemv(u8),
SGemvSplit(u8),
SGemvQ8k(u8),
SGemvQ8kSplit(u8),
SGemvQ80Split(u8),
S2Gemv,
S2GemvQuads,
S2GemvQ8,
S2GemvFastStaged,
S2GemvFastUnstaged,
}
impl Kernel {
/// Export name in `s_gemv_legacy.cu` / its PTX.
pub fn entry(self) -> &'static str {
match self {
Self::SGemv(2) => "leleka_s_gemv_2",
Self::SGemv(4) => "leleka_s_gemv_4",
Self::SGemv(8) => "leleka_s_gemv_8",
Self::SGemvSplit(2) => "leleka_s_gemv_split_2",
Self::SGemvSplit(4) => "leleka_s_gemv_split_4",
Self::SGemvSplit(8) => "leleka_s_gemv_split_8",
Self::SGemvQ8k(4) => "leleka_s_gemv_q8k_4",
Self::SGemvQ8k(8) => "leleka_s_gemv_q8k_8",
Self::SGemvQ8kSplit(4) => "leleka_s_gemv_q8k_split_4",
Self::SGemvQ8kSplit(8) => "leleka_s_gemv_q8k_split_8",
Self::SGemvQ80Split(4) => "leleka_s_gemv_q8_0_split_4",
Self::SGemvQ80Split(8) => "leleka_s_gemv_q8_0_split_8",
Self::S2Gemv => "leleka_s2_gemv",
Self::S2GemvQuads => "leleka_s2_gemv_quads",
Self::S2GemvQ8 => "leleka_s2_gemv_q8",
Self::S2GemvFastStaged => "leleka_s2_gemv_fast_staged",
Self::S2GemvFastUnstaged => "leleka_s2_gemv_fast_unstaged",
_ => unreachable!("planners only construct widths the entry table has"),
}
}
/// Every entry the module exports.
pub const ALL_ENTRIES: [&'static str; 17] = [
"leleka_s_gemv_2",
"leleka_s_gemv_4",
"leleka_s_gemv_8",
"leleka_s_gemv_split_2",
"leleka_s_gemv_split_4",
"leleka_s_gemv_split_8",
"leleka_s_gemv_q8k_4",
"leleka_s_gemv_q8k_8",
"leleka_s_gemv_q8k_split_4",
"leleka_s_gemv_q8k_split_8",
"leleka_s_gemv_q8_0_split_4",
"leleka_s_gemv_q8_0_split_8",
"leleka_s2_gemv",
"leleka_s2_gemv_quads",
"leleka_s2_gemv_q8",
"leleka_s2_gemv_fast_staged",
"leleka_s2_gemv_fast_unstaged",
];
}
/// Everything a caller needs to launch: the entry, the geometry and the `group_shift` argument (log2 of the group; 0 where
/// the kernel takes `group_elems` instead).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Plan {
pub kernel: Kernel,
pub launch: Launch,
pub group_shift: i32,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Error {
/// "<who>: n_in <n> is not a multiple of group_elems <g>"
NInNotGroupMultiple { who: &'static str, n_in: i64, group: i32 },
/// "s_gemv: form says has_offset but offset is null"
OffsetMissing { who: &'static str },
/// "s_gemv: unsupported code_bits <b>"
UnsupportedCodeBits { who: &'static str, bits: i32 },
/// "s_gemv_q8k: code_bits <b> has no Q8_K contract (S2 uses Q8_0; see docs/activation-contract.md)" and the Q8_0 twin
NoActivationContract { who: &'static str, bits: i32 },
/// "<who>: n_in <n> is not a multiple of the Q8_K block 256" (or of 32 for Q8_0 / the S2 launchers' 64 / 4)
NInNotBlockMultiple { who: &'static str, n_in: i64, block: i64 },
/// "<who>: group_elems must be a power of two, got <g>"
GroupNotPowerOfTwo { who: &'static str, group: i32 },
/// "<who>: group_elems <g> is not a multiple of <m>" (4 for the fp16 split kernel, 16 for the Q8 kernels)
GroupNotMultiple { who: &'static str, group: i32, multiple: i32 },
/// "s_gemv_split: threads_per_row must be a power of two in 1..1024, got <t>" (also stricter-than-Original for s2_*)
ThreadsPerRow { who: &'static str, threads: i32 },
/// "s2_gemv_fast: n_in <n> exceeds the 4096-half shared staging limit"
StagingLimit { n_in: i64 },
/// `(unsigned) n_out` would truncate (the grid is one block per row, or ceil(n_out / rows-per-block) blocks).
GridTooLarge { who: &'static str, n_out: i64 },
}
impl Error {
pub fn message(&self) -> String {
match self {
Self::NInNotGroupMultiple { who, n_in, group } => format!("{who}: n_in {n_in} is not a multiple of group_elems {group}"),
Self::OffsetMissing { who } => format!("{who}: form says has_offset but offset is null"),
Self::UnsupportedCodeBits { who, bits } => format!("{who}: unsupported code_bits {bits}"),
Self::NoActivationContract { who, bits } => format!("{who}: code_bits {bits} has no activation contract for this kernel"),
Self::NInNotBlockMultiple { who, n_in, block } => format!("{who}: n_in {n_in} is not a multiple of {block}"),
Self::GroupNotPowerOfTwo { who, group } => format!("{who}: group_elems must be a power of two, got {group}"),
Self::GroupNotMultiple { who, group, multiple } => format!("{who}: group_elems {group} is not a multiple of {multiple}"),
Self::ThreadsPerRow { who, threads } => format!("{who}: threads_per_row must be a power of two in 1..1024, got {threads}"),
Self::StagingLimit { n_in } => {
format!("s2_gemv_fast: n_in {n_in} exceeds the {S2_FAST_MAX_SHARED_HALVES}-half shared staging limit")
}
Self::GridTooLarge { who, n_out } => format!("{who}: n_out {n_out} does not fit a CUDA grid dimension"),
}
}
}
fn grid_for(who: &'static str, blocks: i64) -> Result<u32, Error> {
u32::try_from(blocks).map_err(|_| Error::GridTooLarge { who, n_out: blocks })
}
fn ceil_div(a: i64, b: i64) -> i64 {
(a + b - 1) / b
}
fn group_shift_of(group: i32) -> i32 {
let mut s = 0;
while (1i32 << s) < group {
s += 1;
}
s
}
fn check_tpr(who: &'static str, tpr: i32) -> Result<(), Error> {
if tpr < 1 || tpr > 1024 || (tpr & (tpr - 1)) != 0 { Err(Error::ThreadsPerRow { who, threads: tpr }) } else { Ok(()) }
}
fn bits_u8(who: &'static str, bits: i32, allowed: &[i32], contract: bool) -> Result<u8, Error> {
if allowed.contains(&bits) {
Ok(bits as u8)
} else if contract {
Err(Error::NoActivationContract { who, bits })
} else {
Err(Error::UnsupportedCodeBits { who, bits })
}
}
/// `s_gemv`: one thread per output row, 128 threads, `ceil(n_out / 128)` blocks. `offset_present` is `offset != nullptr`.
pub fn plan_s_gemv(n_in: i64, n_out: i64, form: &SForm, offset_present: bool) -> Result<Option<Plan>, Error> {
const WHO: &str = "s_gemv";
if n_in <= 0 || n_out <= 0 {
return Ok(None);
}
if form.group_elems <= 0 || n_in % form.group_elems as i64 != 0 {
return Err(Error::NInNotGroupMultiple { who: WHO, n_in, group: form.group_elems });
}
if form.has_offset && !offset_present {
return Err(Error::OffsetMissing { who: WHO });
}
let bits = bits_u8(WHO, form.code_bits, &[2, 4, 8], false)?;
let grid = grid_for(WHO, ceil_div(n_out, 128))?;
Ok(Some(Plan { kernel: Kernel::SGemv(bits), launch: Launch { grid: [grid, 1, 1], block: [128, 1, 1], dynamic_shared: 0 }, group_shift: 0 }))
}
/// `s_gemv_split` / `s_gemv_split_async`: one block of `threads_per_row` threads per row, `threads_per_row * 4` bytes of
/// dynamic shared memory for the reduction tree.
pub fn plan_s_gemv_split(n_in: i64, n_out: i64, form: &SForm, threads_per_row: i32, offset_present: bool) -> Result<Option<Plan>, Error> {
const WHO: &str = "s_gemv_split";
if n_in <= 0 || n_out <= 0 {
return Ok(None);
}
check_tpr(WHO, threads_per_row)?;
if form.group_elems <= 0 || (form.group_elems & (form.group_elems - 1)) != 0 {
return Err(Error::GroupNotPowerOfTwo { who: WHO, group: form.group_elems });
}
if form.group_elems % 4 != 0 {
return Err(Error::GroupNotMultiple { who: WHO, group: form.group_elems, multiple: 4 });
}
if n_in % form.group_elems as i64 != 0 {
return Err(Error::NInNotGroupMultiple { who: WHO, n_in, group: form.group_elems });
}
if form.has_offset && !offset_present {
return Err(Error::OffsetMissing { who: WHO });
}
let bits = bits_u8(WHO, form.code_bits, &[2, 4, 8], false)?;
let grid = grid_for(WHO, n_out)?;
Ok(Some(Plan {
kernel: Kernel::SGemvSplit(bits),
launch: Launch { grid: [grid, 1, 1], block: [threads_per_row as u32, 1, 1], dynamic_shared: threads_per_row as u32 * 4 },
group_shift: group_shift_of(form.group_elems),
}))
}
fn q8_form_ok(who: &'static str, form: &SForm, n_in: i64) -> Result<(), Error> {
if form.group_elems <= 0 || n_in % form.group_elems as i64 != 0 {
return Err(Error::NInNotGroupMultiple { who, n_in, group: form.group_elems });
}
if n_in % Q8K_BLOCK_ELEMS as i64 != 0 {
return Err(Error::NInNotBlockMultiple { who, n_in, block: Q8K_BLOCK_ELEMS as i64 });
}
Ok(())
}
/// `s_gemv_q8k`: thread per row, Q8_K activation, 4- and 8-bit forms only (S2 uses Q8_0). 128 threads.
pub fn plan_s_gemv_q8k(n_in: i64, n_out: i64, form: &SForm) -> Result<Option<Plan>, Error> {
const WHO: &str = "s_gemv_q8k";
if n_in <= 0 || n_out <= 0 {
return Ok(None);
}
q8_form_ok(WHO, form, n_in)?;
let bits = bits_u8(WHO, form.code_bits, &[4, 8], true)?;
let grid = grid_for(WHO, ceil_div(n_out, 128))?;
Ok(Some(Plan { kernel: Kernel::SGemvQ8k(bits), launch: Launch { grid: [grid, 1, 1], block: [128, 1, 1], dynamic_shared: 0 }, group_shift: 0 }))
}
/// `s_gemv_q8k_split`: one warp per row, 256 threads (8 rows per block), Q8_K activation.
pub fn plan_s_gemv_q8k_split(n_in: i64, n_out: i64, form: &SForm) -> Result<Option<Plan>, Error> {
const WHO: &str = "s_gemv_q8k_split";
if n_in <= 0 || n_out <= 0 {
return Ok(None);
}
q8_form_ok(WHO, form, n_in)?;
let shift = group_shift_of(form.group_elems);
if (1i32 << shift) != form.group_elems {
return Err(Error::GroupNotPowerOfTwo { who: WHO, group: form.group_elems });
}
if form.group_elems % 16 != 0 {
return Err(Error::GroupNotMultiple { who: WHO, group: form.group_elems, multiple: 16 });
}
let bits = bits_u8(WHO, form.code_bits, &[4, 8], true)?;
let grid = grid_for(WHO, ceil_div(n_out, 8))?;
Ok(Some(Plan { kernel: Kernel::SGemvQ8kSplit(bits), launch: Launch { grid: [grid, 1, 1], block: [256, 1, 1], dynamic_shared: 0 }, group_shift: shift }))
}
/// `s_gemv_q8_0_split`: the same warp-per-row kernel over `block_q8_0` activations (`n_in % 32 == 0` only).
pub fn plan_s_gemv_q8_0_split(n_in: i64, n_out: i64, form: &SForm) -> Result<Option<Plan>, Error> {
const WHO: &str = "s_gemv_q8_0_split";
if n_in <= 0 || n_out <= 0 {
return Ok(None);
}
if n_in % Q8_0_BLOCK_ELEMS as i64 != 0 {
return Err(Error::NInNotBlockMultiple { who: WHO, n_in, block: Q8_0_BLOCK_ELEMS as i64 });
}
if form.group_elems <= 0 || (form.group_elems & (form.group_elems - 1)) != 0 {
return Err(Error::GroupNotPowerOfTwo { who: WHO, group: form.group_elems });
}
if form.group_elems % 16 != 0 {
return Err(Error::GroupNotMultiple { who: WHO, group: form.group_elems, multiple: 16 });
}
let bits = bits_u8(WHO, form.code_bits, &[4, 8], true)?;
let grid = grid_for(WHO, ceil_div(n_out, 8))?;
Ok(Some(Plan {
kernel: Kernel::SGemvQ80Split(bits),
launch: Launch { grid: [grid, 1, 1], block: [256, 1, 1], dynamic_shared: 0 },
group_shift: group_shift_of(form.group_elems),
}))
}
/// `s2_gemv`: the naive S2 kernel, 128 threads per block.
pub fn plan_s2_gemv(n_in: i64, n_out: i64) -> Result<Option<Plan>, Error> {
const WHO: &str = "s2_gemv";
if n_in <= 0 || n_out <= 0 {
return Ok(None);
}
if n_in % S2_QK != 0 {
return Err(Error::NInNotBlockMultiple { who: WHO, n_in, block: S2_QK });
}
let grid = grid_for(WHO, ceil_div(n_out, 128))?;
Ok(Some(Plan { kernel: Kernel::S2Gemv, launch: Launch { grid: [grid, 1, 1], block: [128, 1, 1], dynamic_shared: 0 }, group_shift: 0 }))
}
/// `s2_gemv_quads`: one block per row; the Original only checks `n_in % 4`.
pub fn plan_s2_gemv_quads(n_in: i64, n_out: i64, threads_per_row: i32) -> Result<Option<Plan>, Error> {
const WHO: &str = "s2_gemv_quads";
if n_in <= 0 || n_out <= 0 {
return Ok(None);
}
if n_in % 4 != 0 {
return Err(Error::NInNotBlockMultiple { who: WHO, n_in, block: 4 });
}
check_tpr(WHO, threads_per_row)?;
let grid = grid_for(WHO, n_out)?;
Ok(Some(Plan {
kernel: Kernel::S2GemvQuads,
launch: Launch { grid: [grid, 1, 1], block: [threads_per_row as u32, 1, 1], dynamic_shared: threads_per_row as u32 * 4 },
group_shift: 0,
}))
}
/// `s2_gemv_q8`: S2 weights, `block_q8_0` activations; `n_in` a multiple of 64 (hence of 32).
pub fn plan_s2_gemv_q8(n_in: i64, n_out: i64, threads_per_row: i32) -> Result<Option<Plan>, Error> {
const WHO: &str = "s2_gemv_q8";
if n_in <= 0 || n_out <= 0 {
return Ok(None);
}
if n_in % 32 != 0 || n_in % S2_QK != 0 {
return Err(Error::NInNotBlockMultiple { who: WHO, n_in, block: S2_QK });
}
check_tpr(WHO, threads_per_row)?;
let grid = grid_for(WHO, n_out)?;
Ok(Some(Plan {
kernel: Kernel::S2GemvQ8,
launch: Launch { grid: [grid, 1, 1], block: [threads_per_row as u32, 1, 1], dynamic_shared: threads_per_row as u32 * 4 },
group_shift: 0,
}))
}
/// `s2_gemv_fast` (measured negative in the Original; kept as the experiment record, not a fast path). The constant code
/// table is static in the PTX, so there is no `ensure_lut` step. Dynamic shared memory: `threads_per_row * 4` plus, when
/// `x` is staged, `4096 * 2` bytes in front.
pub fn plan_s2_gemv_fast(n_in: i64, n_out: i64, threads_per_row: i32, stage_x: bool) -> Result<Option<Plan>, Error> {
const WHO: &str = "s2_gemv_fast";
if n_in <= 0 || n_out <= 0 {
return Ok(None);
}
if n_in % 4 != 0 || n_in % S2_QK != 0 {
return Err(Error::NInNotBlockMultiple { who: WHO, n_in, block: S2_QK });
}
check_tpr(WHO, threads_per_row)?;
if stage_x && n_in > S2_FAST_MAX_SHARED_HALVES {
return Err(Error::StagingLimit { n_in });
}
let grid = grid_for(WHO, n_out)?;
let smem = if stage_x { S2_FAST_MAX_SHARED_HALVES as u32 * 2 } else { 0 } + threads_per_row as u32 * 4;
Ok(Some(Plan {
kernel: if stage_x { Kernel::S2GemvFastStaged } else { Kernel::S2GemvFastUnstaged },
launch: Launch { grid: [grid, 1, 1], block: [threads_per_row as u32, 1, 1], dynamic_shared: smem },
group_shift: 0,
}))
}
// ---- CPU models -------------------------------------------------------------------------------------------------------
/// binary16 bits to f32 (exact).
pub fn f16_to_f32(bits: u16) -> f32 {
let sign = if bits & 0x8000 != 0 { -1.0f32 } else { 1.0 };
let exp = ((bits >> 10) & 0x1f) as i32;
let man = (bits & 0x3ff) as f32;
match exp {
0 => sign * man * 2f32.powi(-24),
31 => {
if man == 0.0 {
sign * f32::INFINITY
} else {
f32::NAN
}
}
_ => sign * (1.0 + man / 1024.0) * 2f32.powi(exp - 15),
}
}
/// Code of element `e` of a row: `(c[e / per] >> ((e % per) * bits)) & mask`.
pub fn code_at(row_codes: &[u8], bits: u32, e: usize) -> u32 {
let per = (8 / bits) as usize;
((row_codes[e / per] as u32) >> ((e % per) as u32 * bits)) & ((1u32 << bits) - 1)
}
/// Pack raw codes (each `< 2^bits`) little-endian within each byte.
pub fn pack_codes(raw: &[u8], bits: u32) -> Vec<u8> {
let per = (8 / bits) as usize;
let mut out = vec![0u8; raw.len() / per];
for (e, &c) in raw.iter().enumerate() {
out[e / per] |= c << ((e % per) as u32 * bits);
}
out
}
/// `decode_tbl`: the integer code mapped to a weight before scale/offset.
pub fn decode(code: u32, bias: i32, codebook: Codebook) -> f32 {
match codebook {
Codebook::Iq4Nl => IQ4NL[(code & 0x0f) as usize] as f32,
Codebook::Affine => (code as i32 + bias) as f32,
}
}
/// `block_q8_K` activation to f32 values (`d * q`, the single f32 multiply the kernels perform).
pub fn q8k_dequant(buf: &[u8], n: usize) -> Vec<f32> {
(0..n)
.map(|i| {
let blk = &buf[(i / Q8K_BLOCK_ELEMS) * Q8K_BLOCK_BYTES..];
let d = f32::from_le_bytes([blk[0], blk[1], blk[2], blk[3]]);
d * (blk[4 + i % Q8K_BLOCK_ELEMS] as i8) as f32
})
.collect()
}
/// `block_q8_0` activation to f32 values.
pub fn q8_0_dequant(buf: &[u8], n: usize) -> Vec<f32> {
(0..n)
.map(|i| {
let blk = &buf[(i / Q8_0_BLOCK_ELEMS) * Q8_0_BLOCK_BYTES..];
let d = f16_to_f32(u16::from_le_bytes([blk[0], blk[1]]));
d * (blk[2 + i % Q8_0_BLOCK_ELEMS] as i8) as f32
})
.collect()
}
/// A weight matrix in S-form with its row geometry.
pub struct Weights<'a> {
pub codes: &'a [u8],
pub scales: &'a [f32],
pub offset: Option<&'a [f32]>,
pub form: SForm,
pub n_in: usize,
pub n_out: usize,
}
impl Weights<'_> {
fn per(&self) -> usize {
(8 / self.form.code_bits) as usize
}
fn row_codes(&self, o: usize) -> &[u8] {
let n = self.n_in / self.per();
&self.codes[o * n..(o + 1) * n]
}
/// `decode(code) * d + b` for element `e` of row `o`, exactly the kernels' expression (two roundings).
fn weight(&self, o: usize, e: usize) -> f32 {
let g = o * (self.n_in / self.form.group_elems as usize) + e / self.form.group_elems as usize;
let d = self.scales[g];
let b = self.offset.map_or(0.0, |off| off[g]);
decode(code_at(self.row_codes(o), self.form.code_bits as u32, e), self.form.code_bias, self.form.codebook) * d + b
}
}
/// FP64 specification: `y[o] = sum_i w[o][i] * x[i]`.
pub fn reference_f64(w: &Weights, x: &[f32]) -> Vec<f64> {
(0..w.n_out).map(|o| (0..w.n_in).map(|e| w.weight(o, e) as f64 * x[e] as f64).sum()).collect()
}
/// Literal model of `s_gemv_kernel` / `s2_gemv_kernel`: one accumulator, group by group.
pub fn naive_f32(w: &Weights, x: &[f32]) -> Vec<f32> {
(0..w.n_out)
.map(|o| {
let mut acc = 0.0f32;
for e in 0..w.n_in {
acc += w.weight(o, e) * x[e];
}
acc
})
.collect()
}
/// Literal model of `s_gemv_split_kernel`: per thread a stride of QE=4 consecutive elements into four accumulators,
/// `(a0+a1)+(a2+a3)`, then the shared-memory tree `step = tpr/2 .. 1`.
pub fn split_f32(w: &Weights, x: &[f32], tpr: usize) -> Vec<f32> {
const QE: usize = 4;
(0..w.n_out)
.map(|o| {
let mut partial = vec![0.0f32; tpr];
for (tid, slot) in partial.iter_mut().enumerate() {
let mut a = [0.0f32; QE];
let mut i = tid * QE;
while i + QE <= w.n_in {
for k in 0..QE {
a[k] += w.weight(o, i + k) * x[i + k];
}
i += tpr * QE;
}
while i < w.n_in {
let mut k = 0;
while k < QE && i + k < w.n_in {
a[0] += w.weight(o, i + k) * x[i + k];
k += 1;
}
i += tpr * QE;
}
*slot = (a[0] + a[1]) + (a[2] + a[3]);
}
let mut step = tpr / 2;
while step > 0 {
for tid in 0..step {
partial[tid] += partial[tid + step];
}
step >>= 1;
}
partial[0]
})
.collect()
}
/// Literal model of `s_gemv_q8_split_kernel` (warp per row): lane `l` takes 16 consecutive elements at `l*16 + 512*k` into
/// sixteen accumulators; `acc = (((a0+a1)+(a2+a3))+((a4+a5)+(a6+a7))) + (((a8+a9)+(a10+a11))+((a12+a13)+(a14+a15)))`; lane 0
/// then reads the `__shfl_down_sync` tree with steps 16, 8, 4, 2, 1. `act` holds the dequantised activations (`d * q`).
pub fn q8_split_f32(w: &Weights, act: &[f32]) -> Vec<f32> {
const QE: usize = 16;
(0..w.n_out)
.map(|o| {
let mut lanes = [0.0f32; 32];
for (lane, slot) in lanes.iter_mut().enumerate() {
let mut a = [0.0f32; QE];
let mut i = lane * QE;
while i + QE <= w.n_in {
for k in 0..QE {
a[k] += w.weight(o, i + k) * act[i + k];
}
i += 32 * QE;
}
while i < w.n_in {
let mut k = 0;
while k < QE && i + k < w.n_in {
a[0] += w.weight(o, i + k) * act[i + k];
k += 1;
}
i += 32 * QE;
}
*slot = (((a[0] + a[1]) + (a[2] + a[3])) + ((a[4] + a[5]) + (a[6] + a[7])))
+ (((a[8] + a[9]) + (a[10] + a[11])) + ((a[12] + a[13]) + (a[14] + a[15])));
}
for step in [16usize, 8, 4, 2, 1] {
let old = lanes;
for l in 0..32 {
if l + step < 32 {
lanes[l] = old[l] + old[l + step];
}
}
}
lanes[0]
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::Value;
fn golden() -> Value {
serde_json::from_str(include_str!("../oracle/fixtures/s_gemv_legacy_golden.json")).unwrap()
}
fn u8s(v: &Value) -> Vec<u8> {
v.as_array().unwrap().iter().map(|x| x.as_u64().unwrap() as u8).collect()
}
fn f32s(v: &Value) -> Vec<f32> {
v.as_array().unwrap().iter().map(|x| x.as_f64().unwrap() as f32).collect()
}
fn form(c: &Value) -> SForm {
SForm {
code_bits: c["bits"].as_i64().unwrap() as i32,
code_bias: c["bias"].as_i64().unwrap() as i32,
group_elems: c["group"].as_i64().unwrap() as i32,
codebook: if c["codebook"].as_i64().unwrap() == 1 { Codebook::Iq4Nl } else { Codebook::Affine },
has_offset: c["has_offset"].as_i64().unwrap() == 1,
act_kind: 0,
}
}
fn bits_eq(a: &[f32], b: &[f32], what: &str) {
assert_eq!(a.len(), b.len(), "{what}");
for (i, (x, y)) in a.iter().zip(b).enumerate() {
assert_eq!(x.to_bits(), y.to_bits(), "{what}[{i}]: model {x} vs shim-kernel {y}");
}
}
#[test]
fn golden_cases_match_the_shim_executed_kernels_bit_for_bit() {
let g = golden();
let mut checked = 0;
for c in g["cases"].as_array().unwrap() {
let name = c["name"].as_str().unwrap();
let f = form(c);
let (n_in, n_out) = (c["n_in"].as_u64().unwrap() as usize, c["n_out"].as_u64().unwrap() as usize);
let codes = u8s(&c["codes"]);
let scales = f32s(&c["scales"]);
let offset = if f.has_offset { Some(f32s(&c["offset"])) } else { None };
let w = Weights { codes: &codes, scales: &scales, offset: offset.as_deref(), form: f, n_in, n_out };
let exact = c["exact"].as_i64().unwrap() == 1;
// fp16 activations
let x: Vec<f32> = c["x"].as_array().unwrap().iter().map(|v| f16_to_f32(v.as_u64().unwrap() as u16)).collect();
let y = f32s(&c["y_fp16"]);
bits_eq(&split_f32(&w, &x, 64), &y, &format!("{name} split64"));
if exact {
// every order is exact: the naive kernel, the FP64 spec and the split kernel coincide
bits_eq(&naive_f32(&w, &x), &y, &format!("{name} naive"));
let r: Vec<f32> = reference_f64(&w, &x).iter().map(|&v| v as f32).collect();
bits_eq(&r, &y, &format!("{name} f64"));
}
// Q8_K activations (4- and 8-bit forms with n_in % 256 == 0)
let q8k = u8s(&c["q8k"]);
if f.code_bits != 2 && !q8k.is_empty() {
let a = q8k_dequant(&q8k, n_in);
bits_eq(&q8_split_f32(&w, &a), &f32s(&c["y_q8k"]), &format!("{name} q8k split"));
}
// Q8_0 activations (the S2 entry is s2_gemv_q8, whose tree is the quad kernel's)
let q80 = u8s(&c["q80"]);
if !q80.is_empty() {
let a = q8_0_dequant(&q80, n_in);
let y80 = f32s(&c["y_q80"]);
if f.code_bits != 2 {
bits_eq(&q8_split_f32(&w, &a), &y80, &format!("{name} q8_0 split"));
} else {
assert!(exact);
let r: Vec<f32> = reference_f64(&w, &a).iter().map(|&v| v as f32).collect();
bits_eq(&r, &y80, &format!("{name} s2_gemv_q8"));
}
}
checked += 1;
}
assert_eq!(checked, 8);
}
#[test]
fn pack_unpack_roundtrip_all_widths() {
for bits in [2u32, 4, 8] {
let raw: Vec<u8> = (0..64u32).map(|i| ((i * 37 + 5) & ((1 << bits) - 1)) as u8).collect();
let packed = pack_codes(&raw, bits);
assert_eq!(packed.len(), 64 * bits as usize / 8);
for (e, &r) in raw.iter().enumerate() {
assert_eq!(code_at(&packed, bits, e), r as u32);
}
}
}
#[test]
fn f16_conversion_covers_normal_subnormal_and_special() {
assert_eq!(f16_to_f32(0x3c00), 1.0);
assert_eq!(f16_to_f32(0xc000), -2.0);
assert_eq!(f16_to_f32(0x0001), 2f32.powi(-24));
assert_eq!(f16_to_f32(0x7bff), 65504.0);
assert!(f16_to_f32(0x7c00).is_infinite());
assert!(f16_to_f32(0x7e00).is_nan());
}
#[test]
fn cuda_source_carries_the_codebook_and_every_entry() {
let src = include_str!("s_gemv_legacy.cu");
let table = IQ4NL.iter().map(|v| v.to_string()).collect::<Vec<_>>().join(", ");
let squashed: String = src.split_whitespace().collect::<Vec<_>>().join(" ");
assert!(squashed.contains(&format!("kIq4Nl[16] = {{{table}}};")), "codebook drifted from s_gemv.cu");
for b in [2, 4, 8] {
assert!(src.contains(&format!("LELEKA_S_GEMV({b})")) && src.contains(&format!("LELEKA_S_GEMV_SPLIT({b})")));
}
for b in [4, 8] {
assert!(src.contains(&format!("LELEKA_S_GEMV_Q8K({b})")));
}
for e in Kernel::ALL_ENTRIES {
// macro-expanded entries are checked above through their invocations; the explicit ones by name
let direct = src.contains(&format!("void {e}("));
let via_macro = e.starts_with("leleka_s_gemv_") && !e.contains("q8k_split") && !e.contains("q8_0_split");
let split = (e.contains("q8k_split") || e.contains("q8_0_split")) && src.contains(&format!("LELEKA_S_GEMV_Q8_SPLIT({e},"));
assert!(direct || via_macro || split, "entry {e} not found in s_gemv_legacy.cu");
}
// the s2_gemv_fast code table was generated: row b is [(b>>2k & 3) - 1 for k in 0..4]
assert!(src.contains("{-1.0f, -1.0f, -1.0f, -1.0f},"));
assert!(src.contains("{2.0f, 2.0f, 2.0f, 2.0f}\n};"));
assert!(src.contains("{0.0f, -1.0f, -1.0f, -1.0f},"));
}
#[test]
fn entry_names_are_distinct_and_match_kernel_enum() {
let mut all: Vec<&str> = Kernel::ALL_ENTRIES.to_vec();
all.sort();
all.dedup();
assert_eq!(all.len(), 17);
assert_eq!(Kernel::SGemv(8).entry(), "leleka_s_gemv_8");
assert_eq!(Kernel::SGemvQ80Split(4).entry(), "leleka_s_gemv_q8_0_split_4");
assert_eq!(Kernel::S2GemvFastUnstaged.entry(), "leleka_s2_gemv_fast_unstaged");
}
fn s4() -> SForm {
SForm { code_bits: 4, code_bias: -8, group_elems: 32, codebook: Codebook::Affine, has_offset: false, act_kind: 0 }
}
#[test]
fn plan_s_gemv_geometry_and_refusals() {
let p = plan_s_gemv(2560, 10240, &s4(), false).unwrap().unwrap();
assert_eq!(p.kernel, Kernel::SGemv(4));
assert_eq!(p.launch, Launch { grid: [80, 1, 1], block: [128, 1, 1], dynamic_shared: 0 });
assert_eq!(plan_s_gemv(0, 5, &s4(), false), Ok(None));
assert_eq!(plan_s_gemv(2560, 0, &s4(), false), Ok(None));
assert_eq!(plan_s_gemv(100, 8, &s4(), false), Err(Error::NInNotGroupMultiple { who: "s_gemv", n_in: 100, group: 32 }));
let mut f = s4();
f.has_offset = true;
assert_eq!(plan_s_gemv(64, 8, &f, false), Err(Error::OffsetMissing { who: "s_gemv" }));
assert!(plan_s_gemv(64, 8, &f, true).is_ok());
f.code_bits = 3;
assert_eq!(plan_s_gemv(64, 8, &f, true), Err(Error::UnsupportedCodeBits { who: "s_gemv", bits: 3 }));
assert_eq!(Error::NInNotGroupMultiple { who: "s_gemv", n_in: 100, group: 32 }.message(), "s_gemv: n_in 100 is not a multiple of group_elems 32");
}
#[test]
fn plan_split_uses_a_row_per_block_and_shift_group() {
let f = SForm { code_bits: 2, code_bias: -1, group_elems: 64, ..SForm::default() };
let p = plan_s_gemv_split(2560, 640, &f, 64, false).unwrap().unwrap();
assert_eq!(p.kernel, Kernel::SGemvSplit(2));
assert_eq!(p.group_shift, 6);
assert_eq!(p.launch, Launch { grid: [640, 1, 1], block: [64, 1, 1], dynamic_shared: 256 });
for t in [0, 3, 2048, -1] {
assert_eq!(plan_s_gemv_split(2560, 640, &f, t, false), Err(Error::ThreadsPerRow { who: "s_gemv_split", threads: t }));
}
let odd = SForm { group_elems: 48, ..f };
assert_eq!(plan_s_gemv_split(2560, 8, &odd, 32, false), Err(Error::GroupNotPowerOfTwo { who: "s_gemv_split", group: 48 }));
let two = SForm { group_elems: 2, ..f };
assert_eq!(plan_s_gemv_split(64, 8, &two, 32, false), Err(Error::GroupNotMultiple { who: "s_gemv_split", group: 2, multiple: 4 }));
// stricter than the Original: n_in must be a group multiple
assert!(plan_s_gemv_split(2562, 8, &f, 32, false).is_err());
}
#[test]
fn plan_q8_kernels_enforce_the_activation_contract() {
let f = SForm { code_bits: 4, code_bias: 0, group_elems: 32, codebook: Codebook::Iq4Nl, has_offset: false, act_kind: 1 };
let p = plan_s_gemv_q8k_split(2560, 10240, &f).unwrap().unwrap();
assert_eq!(p.launch, Launch { grid: [1280, 1, 1], block: [256, 1, 1], dynamic_shared: 0 });
assert_eq!(p.group_shift, 5);
assert_eq!(plan_s_gemv_q8k(2560, 10240, &f).unwrap().unwrap().launch.grid, [80, 1, 1]);
// 640 is a multiple of 32 but not of 256: only the Q8_0 kernel serves ffn_down_shexp
assert_eq!(plan_s_gemv_q8k_split(640, 2560, &f), Err(Error::NInNotBlockMultiple { who: "s_gemv_q8k_split", n_in: 640, block: 256 }));
let p0 = plan_s_gemv_q8_0_split(640, 2560, &f).unwrap().unwrap();
assert_eq!(p0.kernel, Kernel::SGemvQ80Split(4));
assert_eq!(p0.launch.grid, [320, 1, 1]);
assert_eq!(plan_s_gemv_q8_0_split(100, 8, &f), Err(Error::NInNotBlockMultiple { who: "s_gemv_q8_0_split", n_in: 100, block: 32 }));
let g8 = SForm { group_elems: 8, ..f };
assert_eq!(plan_s_gemv_q8_0_split(640, 8, &g8), Err(Error::GroupNotMultiple { who: "s_gemv_q8_0_split", group: 8, multiple: 16 }));
let s2 = SForm { code_bits: 2, ..f };
assert!(matches!(plan_s_gemv_q8k(256, 8, &s2), Err(Error::NoActivationContract { bits: 2, .. })));
assert!(matches!(plan_s_gemv_q8k_split(256, 8, &s2), Err(Error::NoActivationContract { bits: 2, .. })));
assert!(matches!(plan_s_gemv_q8_0_split(256, 8, &s2), Err(Error::NoActivationContract { bits: 2, .. })));
}
#[test]
fn plan_s2_kernels() {
assert_eq!(plan_s2_gemv(2560, 300).unwrap().unwrap().launch, Launch { grid: [3, 1, 1], block: [128, 1, 1], dynamic_shared: 0 });
assert!(plan_s2_gemv(100, 8).is_err());
let q = plan_s2_gemv_quads(2560, 640, 32).unwrap().unwrap();
assert_eq!(q.launch, Launch { grid: [640, 1, 1], block: [32, 1, 1], dynamic_shared: 128 });
assert_eq!(plan_s2_gemv_quads(6, 8, 32), Err(Error::NInNotBlockMultiple { who: "s2_gemv_quads", n_in: 6, block: 4 }));
assert!(plan_s2_gemv_quads(64, 8, 24).is_err());
assert_eq!(plan_s2_gemv_q8(640, 8, 64).unwrap().unwrap().launch.dynamic_shared, 256);
assert!(plan_s2_gemv_q8(96, 8, 64).is_err());
let st = plan_s2_gemv_fast(2560, 640, 64, true).unwrap().unwrap();
assert_eq!(st.kernel, Kernel::S2GemvFastStaged);
assert_eq!(st.launch.dynamic_shared, 8192 + 256);
let un = plan_s2_gemv_fast(2560, 640, 64, false).unwrap().unwrap();
assert_eq!((un.kernel, un.launch.dynamic_shared), (Kernel::S2GemvFastUnstaged, 256));
assert_eq!(plan_s2_gemv_fast(8192, 8, 64, true), Err(Error::StagingLimit { n_in: 8192 }));
assert!(plan_s2_gemv_fast(8192, 8, 64, false).is_ok());
}
#[test]
fn grid_overflow_is_refused_not_truncated() {
let f = SForm { code_bits: 2, ..SForm::default() };
let big = (u32::MAX as i64) + 1;
assert!(matches!(plan_s_gemv_split(64, big, &f, 32, false), Err(Error::GridTooLarge { .. })));
}
}