Merge f-quants (945fee23) into f-qwen36: the K-quant CPU pool rows, libstrata_kq, the K-quant GEMV work

This commit is contained in:
Niko1221 committed 2026-10-12 23:48:28 +02:00
commit 3e11f786af
30 files changed
+2113 -126

No files matched your search

+174
View File
@@ -0,0 +1,174 @@
// src/kernels/cpu/kq_cpu_bench.cpp - MODEL-UPDATE: how close the CPU pool's expert rows come to the RAM bandwidth, per
// expert format. No GPU, no model: --mb MB of expert blobs (ggml-quantized random weights, far more than any L3) are
// computed by T threads at once through the engine's own entry points (native_gu_rows + native_down_rows, the pool's
// calls), each thread walking its own experts, nt tokens per expert - the decode case, where every CPU expert is a
// fresh read from DRAM. Prints the weight bytes per second against the --ram-gbs given (a separate read test).
//
// kq_cpu_bench [--pairs q4_K/q5_1,q5_K/q8_0,q6_K/q8_0,q8_0/q8_0,iq3_s/iq4_nl] [--threads 1,8,16,32] [--nt 1,2,4]
// [--mb 4096] [--reps 3] [--ram-gbs N]
#include "strata/kernels/cpu/expert_layout.hpp"
#include "strata/kernels/cpu/native_expert.hpp"
#include "ggml.h"
#include "ggml-cpu.h"
#include <algorithm>
#include <atomic>
#include <chrono>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <memory>
#include <random>
#include <string>
#include <thread>
#include <vector>
namespace cpu = strata::kernels::cpu;
namespace {
constexpr int64_t kH = 2560, kFF = 640;
constexpr int kMaxT = 8;
int type_of(const std::string& s) {
for (int t = 0; t < GGML_TYPE_COUNT; ++t) {
const char* n = ggml_type_name((ggml_type) t);
if (n != nullptr && s == n) return t;
}
return -1;
}
std::vector<std::string> split(const std::string& s) {
std::vector<std::string> v;
size_t from = 0;
for (;;) {
const size_t c = s.find(',', from);
v.push_back(s.substr(from, c == std::string::npos ? std::string::npos : c - from));
if (c == std::string::npos) break;
from = c + 1;
}
return v;
}
// one expert blob in the GGUF form: gate rows, up rows (n_ff x n_embd each), down rows (n_embd x n_ff), from random
// weights quantized by ggml-cpu (valid scales, as a real file has)
void make_blob(const cpu::NativeFmt& f, uint8_t* blob, std::mt19937& rng) {
std::normal_distribution<float> nd(0.f, 0.02f);
std::vector<float> row((size_t) std::max(kH, kFF));
const auto* tg = ggml_get_type_traits_cpu((ggml_type) f.gu_type);
const auto* td = ggml_get_type_traits_cpu((ggml_type) f.d_type);
for (int64_t r = 0; r < 2 * kFF; ++r) {
for (int64_t i = 0; i < kH; ++i) row[(size_t) i] = nd(rng);
tg->from_float(row.data(), blob + (size_t) r * f.gu_row, kH);
}
for (int64_t r = 0; r < kH; ++r) {
for (int64_t i = 0; i < kFF; ++i) row[(size_t) i] = nd(rng);
td->from_float(row.data(), blob + f.down_off + (size_t) r * f.d_row, kFF);
}
}
} // namespace
int main(int argc, char** argv) {
setvbuf(stdout, nullptr, _IONBF, 0);
std::vector<std::string> pairs = split("q4_K/q5_1,q5_K/q8_0,q6_K/q8_0,q8_0/q8_0,iq3_s/iq4_nl");
std::vector<int> threads = {1, 8, 16, 32}, nts = {1, 2, 4};
int mb = 4096, reps = 3;
double ram = 0;
for (int i = 1; i < argc; ++i) {
const std::string a = argv[i];
const bool more = i + 1 < argc;
auto ints = [](const std::string& s) { std::vector<int> v; for (auto& x : split(s)) v.push_back(std::atoi(x.c_str())); return v; };
if (a == "--pairs" && more) pairs = split(argv[++i]);
else if (a == "--threads" && more) threads = ints(argv[++i]);
else if (a == "--nt" && more) nts = ints(argv[++i]);
else if (a == "--mb" && more) mb = std::atoi(argv[++i]);
else if (a == "--reps" && more) reps = std::max(1, std::atoi(argv[++i]));
else if (a == "--ram-gbs" && more) ram = std::atof(argv[++i]);
else {
std::fprintf(stderr, "usage: kq_cpu_bench [--pairs a/b,...] [--threads 1,8] [--nt 1,2,4] [--mb 4096] [--reps 3] [--ram-gbs N]\n");
return 2;
}
}
ggml_cpu_init();
std::printf("kq_cpu_bench: %s (avx2 %d, avx512 %d), %d MB of blobs per format\n", cpu::cpu_name().c_str(),
(int) cpu::cpu_avx2_ok(), (int) cpu::cpu_avx512_ok(), mb);
for (const std::string& pair : pairs) {
const size_t slash = pair.find('/');
const int gt = slash == std::string::npos ? -1 : type_of(pair.substr(0, slash));
const int dt = slash == std::string::npos ? -1 : type_of(pair.substr(slash + 1));
cpu::NativeFmt f;
std::string err;
if (gt < 0 || dt < 0 || !cpu::native_fmt(gt, dt, kH, kFF, f, err)) {
std::printf("%s: %s\n", pair.c_str(), err.empty() ? "unknown types" : err.c_str());
continue;
}
ggml_quantize_init((ggml_type) gt); // the i-quants' quantizers need their grids first
ggml_quantize_init((ggml_type) dt);
const size_t E = std::max<size_t>(64, ((size_t) mb << 20) / f.bytes);
std::unique_ptr<uint8_t[]> mem(new uint8_t[E * f.bytes + 4096]);
uint8_t* blobs = (uint8_t*) (((uintptr_t) mem.get() + 4095) & ~(uintptr_t) 4095);
{ // 16 distinct experts, copied over the whole buffer (the bytes in DRAM are what is measured)
std::mt19937 rng(1234 + gt * 64 + dt);
const size_t U = std::min<size_t>(16, E);
for (size_t e = 0; e < U; ++e) make_blob(f, blobs + e * f.bytes, rng);
for (size_t e = U; e < E; ++e) std::memcpy(blobs + e * f.bytes, blobs + (e % U) * f.bytes, f.bytes);
}
// activations: kMaxT tokens of x (n_embd) and h (n_ff), quantized the way the pool quantizes them
std::mt19937 rng(77);
std::normal_distribution<float> nd(0.f, 1.f);
std::vector<std::vector<uint8_t>> xa(kMaxT, std::vector<uint8_t>(cpu::kNativeActBytes)),
ha(kMaxT, std::vector<uint8_t>(cpu::kNativeHBytes));
const void* act[kMaxT];
const void* hq[kMaxT];
for (int t = 0; t < kMaxT; ++t) {
std::vector<float> x(kH), h(kFF);
for (auto& v : x) v = nd(rng);
for (auto& v : h) v = 0.1f * nd(rng);
cpu::native_quant_act(f, x.data(), xa[t].data());
cpu::native_quant_h(f, h.data(), ha[t].data());
act[t] = xa[t].data();
hq[t] = ha[t].data();
}
std::printf("\n%s: %zu experts of %.3f MB (%.0f MB)\n", pair.c_str(), E, f.bytes / 1e6, E * (double) f.bytes / 1e6);
for (int nt : nts) {
for (int T : threads) {
if (T < 1) continue;
std::vector<double> gbs;
for (int rep = 0; rep < reps; ++rep) {
std::atomic<size_t> next{0};
auto work = [&] {
std::vector<float> ffb((size_t) kMaxT * kFF), outb((size_t) kMaxT * kH);
float* ff[kMaxT];
float* out[kMaxT];
for (int t = 0; t < kMaxT; ++t) { ff[t] = &ffb[(size_t) t * kFF]; out[t] = &outb[(size_t) t * kH]; }
std::vector<std::vector<uint8_t>> hb(kMaxT, std::vector<uint8_t>(cpu::kNativeHBytes));
for (;;) {
const size_t e = next.fetch_add(1);
if (e >= E) break;
const uint8_t* blob = blobs + e * f.bytes;
cpu::native_gu_rows(f, blob, act, nt, ff, 0, (int) kFF);
cpu::native_down_rows(f, blob, hq, nt, out, 0, (int) kH);
}
volatile float sink = outb[0] + ffb[0];
(void) sink;
};
const auto t0 = std::chrono::steady_clock::now();
std::vector<std::thread> th;
for (int k = 0; k < T; ++k) th.emplace_back(work);
for (auto& x : th) x.join();
const double s = std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
gbs.push_back(E * (double) f.bytes / s / 1e9);
}
std::sort(gbs.begin(), gbs.end());
const double med = gbs[gbs.size() / 2];
std::printf(" nt %d threads %2d: %6.1f GB/s of weights (%.3f ms per expert per thread)%s\n", nt, T, med,
f.bytes / (med * 1e9 / T) * 1e3,
ram > 0 ? (" = " + std::to_string((int) std::lround(100 * med / ram)) + "% of RAM").c_str() : "");
}
}
}
return 0;
}
+46 -1
View File
@@ -27,6 +27,7 @@
#include "strata/kernels/dp4a.hpp"
#include "strata/kernels/q8_1_finite.hpp"
#include "strata/kernels/iq_kernels.hpp"
#include "strata/kernels/gfx_arch.hpp"
#include "s26_tsum.cuh"
#if !defined(__HIPCC__)
#include "q8_1_il.cuh"
@@ -42,6 +43,7 @@
#include <cstring>
#include <limits>
#include <stdexcept>
#include <type_traits>
#include <string>
#include <unordered_map>
#include <cstdio>
@@ -1258,6 +1260,49 @@ __global__ void native_mmvq_multi_kernel(const typename F::Block* __restrict__ w
}
}
// MODEL-UPDATE: the dense Q8_0 projections of Unsloth's files (all of attention, SSM and the shared expert are Q8_0
// there) take one row per block where that was measured faster - the same per-row sums and reduction as two rows per
// block (each row its own partials), so every output is the same bits. q8_gemv_bench, 2-4 columns:
// gfx1201 (R9700): n_in <= 4096 with n_out >= 4096 (qkv 2560->10240 73-79% -> 83-84% of the 644 GB/s, gate 2560->6144
// 51-68% -> 76-78%, q 2560->12288 74-80% -> 85-86%); 6144->2560 is slower there (79% -> 55-59%) and keeps two rows.
// sm_86 (RTX A4000): every n_out >= 2048 (+1-4% at 2-4 columns, 6144->2560 at 6 columns 70% -> 76%).
// Other cards keep two rows until measured (STRATA_NO_MMVQ_ROWS2=1 forces one row everywhere; =0 keeps two everywhere).
int dev_class() { // 1 = gfx12, 2 = sm_86, 0 = the rest; per device
static int cls[16]; // 0 unknown, else class + 1
int dev = 0;
if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 16) return 0;
if (cls[dev] == 0) {
int c = 0;
#if defined(__HIPCC__)
cudaDeviceProp p;
if (cudaGetDeviceProperties(&p, dev) == cudaSuccess && strata::kernels::gfx_arch_is_gfx12(p.gcnArchName)) c = 1;
#else
int major = 0, minor = 0;
if (cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev) == cudaSuccess &&
cudaDeviceGetAttribute(&minor, cudaDevAttrComputeCapabilityMinor, dev) == cudaSuccess && major == 8 && minor == 6)
c = 2;
#endif
(void) cudaGetLastError();
cls[dev] = c + 1;
}
return cls[dev] - 1;
}
template<typename F>
bool q8_0_rows1(int n_in, int n_out) {
if constexpr (!std::is_same_v<F, SmallTraits<Q80Block, 8>>) {
(void) n_in; (void) n_out;
return false;
} else {
static const int env = [] {
const char* v = std::getenv("STRATA_NO_MMVQ_ROWS2");
return v == nullptr || v[0] == '\0' ? -1 : v[0] != '0';
}();
if (env == 0) return false;
const int c = dev_class();
return (c == 1 && n_in <= 4096 && n_out >= 4096) || (c == 2 && n_out >= 2048);
}
}
template<typename F, int NCOLS>
void launch_multi_n(const void* weights, const void* x_q8_1, float* y, int n_in, int n_out, cudaStream_t s) {
const auto* w = static_cast<const typename F::Block*>(weights);
@@ -1279,7 +1324,7 @@ void launch_multi_n(const void* weights, const void* x_q8_1, float* y, int n_in,
const char* v = std::getenv("STRATA_NO_MMVQ_ROWS2");
return v != nullptr && v[0] != '\0' && v[0] != '0';
}();
if (rows1 && n_in / F::DIV >= F::BPI) {
if ((rows1 || q8_0_rows1<F>(n_in, n_out)) && n_in / F::DIV >= F::BPI) {
if (s26_tsum_on()) launch_pdl(native_mmvq_multi_kernel<F, NCOLS, WARPS, 1, true, false>, dim3(unsigned(n_out)), threads, 0, s, w, x, y, n_in, n_out, no_w2, no_y2);
else launch_pdl(native_mmvq_multi_kernel<F, NCOLS, WARPS, 1, false, false>, dim3(unsigned(n_out)), threads, 0, s, w, x, y, n_in, n_out, no_w2, no_y2);
return;
+109
View File
@@ -0,0 +1,109 @@
// src/kernels/q8_gemv_bench.cpp - MODEL-UPDATE: the dense Q8_0 GEMVs of Unsloth's files (attention, SSM, shared expert,
// hyper-connections, head: all Q8_0 there) at the engine's shapes, 1..6 columns (a verify window's tokens), through
// native_mmvq - the call the engine makes - against the card's memory bandwidth. Enough copies of each matrix are
// cycled to miss the GPU's last-level cache, as a layer's call does.
//
// build/q8_gemv_bench [--cols 1,2,3,4,6] [--iters 50] [--bw GB/s]
#include "strata/kernels/native_mmvq.hpp"
#include <cuda_runtime.h>
#include <algorithm>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <random>
#include <string>
#include <vector>
namespace K = strata::kernels;
namespace {
struct Shape { const char* what; int n_in, n_out; };
const Shape SHAPES[] = {
{"GDN qkv 2560->10240", 2560, 10240}, {"GDN gate 2560->6144", 2560, 6144}, {"GDN/QSA out 6144->2560", 6144, 2560},
{"QSA q 2560->12288", 2560, 12288}, {"QSA k/v 2560->512", 2560, 512}, {"HC down 10240->320", 10240, 320},
{"HC up 320->10240", 320, 10240}, {"shared gate/up 2560->640", 2560, 640}, {"shared down 640->2560", 640, 2560},
{"head 2560->248320", 2560, 248320},
};
void ck(cudaError_t e, const char* w) {
if (e != cudaSuccess) { std::fprintf(stderr, "%s: %s\n", w, cudaGetErrorString(e)); std::exit(1); }
}
std::vector<int> ints(const std::string& s) {
std::vector<int> v;
size_t from = 0;
for (;;) {
const size_t c = s.find(',', from);
v.push_back(std::atoi(s.substr(from, c == std::string::npos ? std::string::npos : c - from).c_str()));
if (c == std::string::npos) break;
from = c + 1;
}
return v;
}
} // namespace
int main(int argc, char** argv) {
std::vector<int> cols = {1, 2, 3, 4, 6};
int iters = 50;
double bw = 0;
for (int i = 1; i < argc; ++i) {
const std::string a = argv[i];
if (a == "--cols" && i + 1 < argc) cols = ints(argv[++i]);
else if (a == "--iters" && i + 1 < argc) iters = std::atoi(argv[++i]);
else if (a == "--bw" && i + 1 < argc) bw = std::atof(argv[++i]);
}
cudaDeviceProp prop;
ck(cudaGetDeviceProperties(&prop, 0), "props");
std::printf("q8_gemv_bench: %s\n", prop.name);
std::mt19937 rng(7);
for (const Shape& s : SHAPES) {
const size_t bytes = (size_t) s.n_out * (s.n_in / 32) * 34;
const int copies = (int) std::max<size_t>(1, std::min<size_t>(16, ((size_t) 512 << 20) / bytes));
std::vector<uint8_t> host(bytes);
for (size_t b = 0; b < bytes; b += 34) { // fp16 scale 0.01 (0x211f), then random int8 weights
host[b] = 0x1f;
host[b + 1] = 0x21;
for (int k = 0; k < 32; ++k) host[b + 2 + k] = (uint8_t) (rng() & 0xff);
}
std::vector<void*> w(copies);
for (auto& p : w) {
ck(cudaMalloc(&p, bytes), "malloc w");
ck(cudaMemcpy(p, host.data(), bytes, cudaMemcpyHostToDevice), "copy w");
}
const int maxc = *std::max_element(cols.begin(), cols.end());
std::vector<float> xh((size_t) s.n_in * maxc);
for (auto& v : xh) v = std::normal_distribution<float>(0.f, 1.f)(rng);
float *x = nullptr, *y = nullptr;
void* xq = nullptr;
ck(cudaMalloc(&x, xh.size() * 4), "x");
ck(cudaMemcpy(x, xh.data(), xh.size() * 4, cudaMemcpyHostToDevice), "x copy");
ck(cudaMalloc(&xq, K::native_q8_1_bytes(s.n_in, maxc)), "xq");
ck(cudaMalloc(&y, (size_t) s.n_out * maxc * 4), "y");
cudaStream_t st;
ck(cudaStreamCreate(&st), "stream");
cudaEvent_t e0, e1;
cudaEventCreate(&e0);
cudaEventCreate(&e1);
std::printf("\n%s: %.2f MB, %d copies\n", s.what, bytes / 1e6, copies);
for (int c : cols) {
K::native_quantize_q8_1(x, xq, s.n_in, c, st);
for (int i = 0; i < 3; ++i) K::native_mmvq(8, w[i % copies], xq, y, s.n_in, s.n_out, c, st);
cudaEventRecord(e0, st);
for (int i = 0; i < iters; ++i) K::native_mmvq(8, w[i % copies], xq, y, s.n_in, s.n_out, c, st);
cudaEventRecord(e1, st);
ck(cudaEventSynchronize(e1), "sync");
float ms = 0;
cudaEventElapsedTime(&ms, e0, e1);
const double us = 1000.0 * ms / iters, gbs = bytes / (us * 1e3);
std::printf(" %d col%s: %8.1f us %7.1f GB/s%s\n", c, c == 1 ? " " : "s", us, gbs,
bw > 0 ? (" = " + std::to_string((int) (100 * gbs / bw + 0.5)) + "% of bw").c_str() : "");
}
for (auto p : w) cudaFree(p);
cudaFree(x);
cudaFree(xq);
cudaFree(y);
cudaStreamDestroy(st);
}
return 0;
}
+60
View File
@@ -0,0 +1,60 @@
// src/prefill/mmq_kq_lib.cu - strata_kq, the shared library with llama.cpp's MMQ prompt kernels for the K-quants
// (Q4_K, Q5_K, Q5_1, Q6_K: the experts of Unsloth's UD-Q4/Q5/Q6_K_XL files). MODEL-UPDATE Phase 1: the engine loads
// every kernel of its own binary when it starts (CUDA_MODULE_LOADING=EAGER, src/program/generate.cpp), so kernels in
// the engine cost every model VRAM; these four instances were ~3.8 MB of sm_60 code (3 expert slots of IQ3_XXS on a
// P100). Here they load only when moe_mmq.cu opens this library - for a model with these experts, before the expert
// cache is sized - and never otherwise. The library has its own copy of ggml_cuda_host.cu's symbols and of the static
// CUDA runtime; it works in the engine's context on the stream it is given.
#include "common.cuh"
#include "mmq.cuh"
#include "strata/prefill/mmq_kq_abi.hpp"
#include <mutex>
#if defined(_WIN32)
#define STRATA_KQ_EXPORT extern "C" __declspec(dllexport)
#else
#define STRATA_KQ_EXPORT extern "C" __attribute__((visibility("default")))
#endif
namespace {
std::mutex g_mu;
ggml_backend_cuda_context* g_ctx[GGML_CUDA_MAX_DEVICES] = {};
ggml_backend_cuda_context* ctx_for(int dev) {
std::lock_guard<std::mutex> lk(g_mu);
if (g_ctx[dev] == nullptr) g_ctx[dev] = new ggml_backend_cuda_context(dev);
return g_ctx[dev];
}
} // namespace
// the interface version and the argument block's size: both sides are compiled from the same mmq.cuh
STRATA_KQ_EXPORT int strata_kq_abi() { return STRATA_KQ_ABI_VERSION * 100000 + (int) sizeof(mmq_args); }
// Starts this library's CUDA runtime in the engine's context on `device`: with CUDA_MODULE_LOADING=EAGER (the engine
// sets it before its first CUDA call) that loads every kernel here now, while the VRAM for it is still free.
// 0 = ready, else the cudaError_t.
STRATA_KQ_EXPORT int strata_kq_init(int device) {
cudaError_t e = cudaSetDevice(device);
if (e == cudaSuccess) e = cudaFree(nullptr);
return (int) e;
}
// One MMQ product (moe_mmq.cu's Context::run for these types) on `device`, on the engine's `stream`. 0 = launched, -1 =
// a type this library does not have, else the cudaError_t of the launch.
STRATA_KQ_EXPORT int strata_kq_run(int device, int type, const void* args, void* stream) {
if (device < 0 || device >= GGML_CUDA_MAX_DEVICES) return -1;
if (cudaSetDevice(device) != cudaSuccess) return (int) cudaGetLastError();
ggml_backend_cuda_context& ctx = *ctx_for(device);
const mmq_args& a = *(const mmq_args*) args;
const cudaStream_t s = (cudaStream_t) stream;
switch ((ggml_type) type) {
case GGML_TYPE_Q4_K: mul_mat_q_case<GGML_TYPE_Q4_K>(ctx, a, s); break;
case GGML_TYPE_Q5_K: mul_mat_q_case<GGML_TYPE_Q5_K>(ctx, a, s); break;
case GGML_TYPE_Q5_1: mul_mat_q_case<GGML_TYPE_Q5_1>(ctx, a, s); break;
case GGML_TYPE_Q6_K: mul_mat_q_case<GGML_TYPE_Q6_K>(ctx, a, s); break;
default: return -1;
}
return (int) cudaGetLastError();
}
+124
View File
@@ -0,0 +1,124 @@
// src/prefill/mmq_kq_loader.cpp - opens strata_kq (src/prefill/mmq_kq_lib.cu), the library with the K-quant MMQ prompt
// kernels, from the engine's own folder - once, for the first model format that asks for it (moe_mmq.cu's supported()),
// which the engine does before it sizes the expert cache (src/program/generate.cpp). Without the library, or with an
// interface of another version, the K-quants keep the FP16 prompt path and the engine says so once.
#include "strata/prefill/mmq_kq_abi.hpp"
#include <cuda_runtime.h>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <mutex>
#include <string>
#if defined(_WIN32)
#ifndef NOMINMAX
#define NOMINMAX
#endif
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#else
#include <dlfcn.h>
#include <unistd.h>
#endif
namespace strata::prefill::mmq::kq {
namespace {
struct Lib {
bool ok = false;
strata_kq_run_fn run = nullptr;
};
std::string own_folder() {
#if defined(_WIN32)
char p[MAX_PATH] = {};
const DWORD n = GetModuleFileNameA(nullptr, p, MAX_PATH);
std::string s(p, n);
const size_t k = s.find_last_of("\\/");
return k == std::string::npos ? std::string() : s.substr(0, k + 1);
#else
char p[4096] = {};
const ssize_t n = readlink("/proc/self/exe", p, sizeof(p) - 1);
std::string s(p, n > 0 ? (size_t) n : 0);
const size_t k = s.find_last_of('/');
return k == std::string::npos ? std::string() : s.substr(0, k + 1);
#endif
}
void* sym(void* h, const char* name) {
#if defined(_WIN32)
return reinterpret_cast<void*>(GetProcAddress((HMODULE) h, name));
#else
return dlsym(h, name);
#endif
}
Lib open_lib() {
Lib L;
const std::string path = own_folder() + STRATA_KQ_LIB_NAME;
#if defined(_WIN32)
void* h = (void*) LoadLibraryA(path.c_str());
#else
void* h = dlopen(path.c_str(), RTLD_NOW | RTLD_LOCAL);
#endif
if (h == nullptr) {
std::fprintf(stderr, "strata: K-quant prompt kernels (STRATA_MMQ_KQ=1): %s not found next to the engine - "
"these experts take the FP16 prompt path\n", STRATA_KQ_LIB_NAME);
return L;
}
const auto abi = (strata_kq_abi_fn) sym(h, "strata_kq_abi");
const auto init = (strata_kq_init_fn) sym(h, "strata_kq_init");
L.run = (strata_kq_run_fn) sym(h, "strata_kq_run");
if (abi == nullptr || init == nullptr || L.run == nullptr || abi() / 100000 != STRATA_KQ_ABI_VERSION ||
abi() % 100000 != abi_args_size()) {
std::fprintf(stderr, "strata: K-quant prompt kernels: %s is from another engine version - these experts take "
"the FP16 prompt path\n", path.c_str());
L.run = nullptr;
return L;
}
// every GPU this engine sees: each context loads the library's kernels now, while the VRAM is still free
int n = 0, cur = 0;
cudaGetDevice(&cur);
if (cudaGetDeviceCount(&n) != cudaSuccess) n = 0;
for (int d = 0; d < n; ++d) {
const int e = init(d);
if (e != 0) {
std::fprintf(stderr, "strata: K-quant prompt kernels: %s did not start on GPU %d (CUDA error %d) - these "
"experts take the FP16 prompt path\n", path.c_str(), d, e);
L.run = nullptr;
cudaSetDevice(cur);
return L;
}
}
cudaSetDevice(cur);
std::fprintf(stderr, "strata: K-quant prompt kernels from %s (STRATA_MMQ_KQ=1)\n", path.c_str());
L.ok = true;
return L;
}
const Lib& lib() {
static const Lib L = open_lib();
return L;
}
} // namespace
bool wanted() {
static const bool on = [] {
const char* v = std::getenv("STRATA_MMQ_KQ");
return v != nullptr && v[0] == '1';
}();
return on;
}
bool available() { return wanted() && lib().ok; }
int run(int type, const void* args, void* stream) {
int dev = 0;
cudaGetDevice(&dev);
return lib().ok ? lib().run(dev, type, args, stream) : -1;
}
} // namespace strata::prefill::mmq::kq
+37 -9
View File
@@ -7,11 +7,33 @@
#include "mmq.cuh"
#include "quantize.cuh"
#include "strata/prefill/mmq_kq_abi.hpp"
#include <cstdio>
#include <cstdlib>
namespace strata::prefill::mmq {
#if defined(STRATA_KQ_DSO)
namespace kq {
int abi_args_size() { return (int) sizeof(mmq_args); }
} // namespace kq
#endif
namespace {
#if defined(STRATA_MMQ_KQUANTS)
// MODEL-UPDATE Phase 1: the K-quant products through MMQ are opt-in at run time (STRATA_MMQ_KQ=1); on CUDA their
// kernels are the strata_kq library (mmq_kq_loader.cpp), opened only then
bool kq_ok() {
#if defined(STRATA_KQ_DSO)
return kq::available();
#else
static const bool on = [] {
const char* v = std::getenv("STRATA_MMQ_KQ");
return v != nullptr && v[0] == '1';
}();
return on;
#endif
}
#endif
void ck(cudaError_t e, const char* what) {
if (e != cudaSuccess) {
@@ -127,13 +149,12 @@ bool supported(int t) {
case GGML_TYPE_IQ2_XXS: case GGML_TYPE_IQ2_XS: case GGML_TYPE_IQ2_S:
case GGML_TYPE_IQ3_XXS: case GGML_TYPE_IQ3_S: case GGML_TYPE_IQ4_NL: case GGML_TYPE_IQ4_XS:
case GGML_TYPE_Q8_0: // the draft layer's dense matrices (E-9)
#ifdef STRATA_MMQ_KQUANTS
case GGML_TYPE_Q4_K: case GGML_TYPE_Q5_K: case GGML_TYPE_Q5_1: // Unsloth's UD-Q4_K_XL experts (CUDA)
#if defined(__HIPCC__) || defined(STRATA_Q6K_EXPERTS)
case GGML_TYPE_Q6_K: // HIP: the dense GGUF projections (STRATA_DENSE_MMQ); CUDA: only the opt-in -DSTRATA_Q6K_EXPERTS=ON build
#endif
#endif
return true;
#ifdef STRATA_MMQ_KQUANTS
// Unsloth's UD-Q4/Q5/Q6_K_XL experts; on HIP also the dense GGUF projections (STRATA_DENSE_MMQ)
case GGML_TYPE_Q4_K: case GGML_TYPE_Q5_K: case GGML_TYPE_Q5_1: case GGML_TYPE_Q6_K:
return kq_ok();
#endif
default:
return false;
}
@@ -213,12 +234,19 @@ void Context::run(const Product& p, void* stream) {
case GGML_TYPE_IQ4_NL: mul_mat_q_case<GGML_TYPE_IQ4_NL>(ctx, a, s); break;
case GGML_TYPE_IQ4_XS: mul_mat_q_case<GGML_TYPE_IQ4_XS>(ctx, a, s); break;
case GGML_TYPE_Q8_0: mul_mat_q_case<GGML_TYPE_Q8_0>(ctx, a, s); break;
#ifdef STRATA_MMQ_KQUANTS
#if defined(STRATA_MMQ_KQUANTS) && defined(STRATA_KQ_DSO)
case GGML_TYPE_Q4_K: case GGML_TYPE_Q5_K: case GGML_TYPE_Q6_K: case GGML_TYPE_Q5_1: {
const int e = kq::run((int) t, &a, s);
if (e != 0) {
std::fprintf(stderr, "prefill mmq: the K-quant library failed on type %d (error %d)\n", (int) t, e);
std::exit(1);
}
break;
}
#elif defined(STRATA_MMQ_KQUANTS)
case GGML_TYPE_Q4_K: mul_mat_q_case<GGML_TYPE_Q4_K>(ctx, a, s); break;
case GGML_TYPE_Q5_K: mul_mat_q_case<GGML_TYPE_Q5_K>(ctx, a, s); break;
#if defined(__HIPCC__) || defined(STRATA_Q6K_EXPERTS)
case GGML_TYPE_Q6_K: mul_mat_q_case<GGML_TYPE_Q6_K>(ctx, a, s); break;
#endif
case GGML_TYPE_Q5_1: mul_mat_q_case<GGML_TYPE_Q5_1>(ctx, a, s); break;
#endif
default:
+9
View File
@@ -62,6 +62,9 @@
#include "strata/core/verify.hpp"
#include "strata/core/mtp.hpp"
#include "strata/prefill/prefill.hpp"
#if defined(STRATA_PREFILL_MMQ)
#include "strata/prefill/moe_mmq.hpp"
#endif
#include "strata/core/native_dense.hpp"
#include "strata/program/batch_read.hpp"
#include "strata/program/logits_selection.hpp"
@@ -2770,6 +2773,12 @@ int main(int argc, char** argv) {
f.gu_type, f.d_type);
return 1;
}
#if defined(STRATA_PREFILL_MMQ)
// MODEL-UPDATE Phase 1: the K-quants' prompt kernels (STRATA_MMQ_KQ=1) are a library of their own on CUDA
// (strata_kq): asking for the formats opens it now, before the expert cache takes the free VRAM
(void) strata::prefill::mmq::supported(f.gu_type);
(void) strata::prefill::mmq::supported(f.d_type);
#endif
}
}
const bool native_pack = strata::kernels::cpu::expert_layout().native;