Skip to content

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

C++

sm_60: a Q8_0 decode GEMV for Pascal GP100 (STRATA_Q8_SM60=1, opt-in)

Niko12216e29a5d3141f
diff --git a/docs/OLDER_GPUS.md b/docs/OLDER_GPUS.md
index dc811c9b0..b653dcd09 100644
--- a/docs/OLDER_GPUS.md
+++ b/docs/OLDER_GPUS.md
@@ -11,7 +11,7 @@ and their output stay exactly as they were. Numbers are the reporters' own, on o
| Cards | Compute capability | How it runs | What is different on it | Reported |
| --- | --- | --- | --- | --- |
-| Tesla P100 | 6.0 | the CUDA 12 engine | `__dp4a` emulated (bit-exact); BF16 projections through fp32 | 2x P100, IQ3_S, engine 0.1.39: prompt 526-532 tok/s, decode 28-32 tok/s at 128K prompt tokens, 3 of 3 needle checks at 122K ([report](../bench/results/2026-10-06-community-2x-p100/README.md), #1157) |
+| Tesla P100 | 6.0 | the CUDA 12 engine | `__dp4a` emulated (bit-exact); BF16 projections through fp32; opt-in: `STRATA_Q8_SM60=1` runs the Q8_0 dense projections and head on a GP100 kernel ([below](#pascal-gp100-a-q8_0-decode-kernel-opt-in)) | 2x P100, IQ3_S, engine 0.1.39: prompt 526-532 tok/s, decode 28-32 tok/s at 128K prompt tokens, 3 of 3 needle checks at 122K ([report](../bench/results/2026-10-06-community-2x-p100/README.md), #1157); PH402 (4 GP100 dies), IQ3_XXS: decode 28.3 -> 38.9 tok/s with `STRATA_Q8_SM60=1` and a Q8_0 dense shard |
| Tesla P40 / P4, GTX 10 series | 6.1 | the CUDA 12 engine | BF16 projections through fp32 (cuBLAS has no BF16 GEMM there, #395); the dense weights dequantized by a wide kernel, expert mode 8 and its own interleaved-matvec table; opt-in `STRATA_DENSE_F32=1`: the large dense GEMMs as `cublasSgemm` ([below](#tesla-p40-sm_61-what-was-measured-and-changed)) | P40, IQ3_S, engine 0.1.30: prompt 217-374 tok/s, decode 30-33 tok/s (#395); 0.1.43.1 with the sm_61 changes: prompt 255 tok/s at 565 tokens (was 205), decode 37-38 tok/s (was 34-35); with `STRATA_DENSE_F32=1` 464-474 tok/s at 7K tokens (was 360-432) |
| Tesla V100, Titan V | 7.0 | the CUDA 12 engine | BF16 projections on the FP16 tensor cores (#655, #540); the prompt attention on `mma.m8n8k4` (#600); a leaner attention kernel (#540) | V100-PCIE-32GB, UD-IQ4_XS: prompt 1,123-1,251 tok/s (#600); V100 32GB, IQ2_XS: prompt +22% from #540 |
| RTX 20 (Turing) | 7.5 | **supported**, the ready-made engine | opt-in: `STRATA_BF16_TC=1` runs the BF16 projections on the FP16 tensor cores | RTX 2080 Ti, Q2_0: prompt +15-18% (#655) |
@@ -95,8 +95,50 @@ sums round differently): #540 measured a mean KL of 8.4e-3 on the next-token dis
(the same top-1 in 23), the size of other summation-order changes; #655 a worst relative difference of 3.5e-5 per
product on an RTX 2080 Ti.
+### Pascal GP100: a Q8_0 decode kernel (opt-in)
+
+GP100 (P100, PH402) is the one Pascal chip without `__dp4a`, and the decode kernels are written for the cards that have
+it: on a GP100 die the dense projections of a verify window read their weights at 40-80 GB/s of its ~730, decoding K-
+and i-quant blocks (Q6_K, IQ4_XS, Q4_K, IQ3_S, ...) one int at a time. Two changes, both measured on a PH402 only:
+
+- **`STRATA_Q8_SM60=1`** packs every Q8_0 dense matrix and the head into the planes of `STRATA_Q8_PACKED` (any shape)
+ and runs them on `src/kernels/cuda/q8_sm60.cuh`: a warp (half or quarter warp for narrow rows) per row, 16-byte
+ weight loads, the window's q8_1 activations copied once per workgroup into shared memory as an int8 plane, the dot
+ on `STRATA_DP4A` (vmad), a shuffle sum - no barrier per row. Shapes it declines (a 6144-wide row with 7-8 columns)
+ keep the usual kernel. Not bitwise the exact kernels (the per-32 products are added in another order). The packed
+ copies cost their size in VRAM beside the GGUF layout the prompt path reads (Flash-Next: 2.9 GiB of dense
+ projections over the stages and 0.6 GiB for the head).
+- The GSQ-RCO packs have no Q8_0 dense matrices, so the kernel needs a shard whose dense projections and head are
+ Q8_0: `python tools/q8_dense_gguf.py <model>-00001-of-00002.gguf <new folder>` writes one (+3.5 GiB; the experts keep
+ their offsets, so the native pack is reused; the other shards are hard-linked beside it). Point `--native` and
+ `--ple-gguf` at the new folder. Requantizing costs at most 0.4% of a tensor's |w|max (Q8_0 is finer than the
+ sources).
+- IQ3_XXS's codebook and sign-mask tables are staged in shared memory by the grouped expert kernels on compute
+ capability 6.x (ported from shinbunbun/llama-cpp-p100-patches 29 and 30; bitwise the same output;
+ `STRATA_IQ_STAGE_GRID18=0|1` forces it off or on, on any card). Within noise on the PH402 (+0-4%).
+
+Measured on a PH402 SKU 200 (two boards, four GP100 dies of 48 SMs and 32 GB HBM2), application clocks locked at
+1050 MHz, Windows 11, driver 581.80 (TCC), CUDA 12.9, engine 0.1.40.2; Flash-Next IQ3_XXS, 32K, `--layer-split 12,24,36
+--prefill 2048`; greedy, 256 tokens, medians of 2-3 interleaved starts, decode tok/s:
+
+| | ~10.7K-token document | the same, cached | short reasoning | code | mean |
+| --- | ---: | ---: | ---: | ---: | ---: |
+| GSQ-RCO shard, exact kernels | 28.8 | 29.4 | 28.4 | 26.8 | 28.3 |
+| Q8_0 dense shard, `STRATA_Q8_PACKED=1` | 27.5 | 31.0 | 34.4 | 31.8 | 31.1 |
+| Q8_0 dense shard, `STRATA_Q8_SM60=1` | 37.5 | 38.4 | 41.2 | 38.5 | 38.9 |
+
+GPU time per verify window (`STRATA_VERIFY_PROFILE`): dense projections 19.2 -> 11.2 ms, head 4.25 -> 2.1 ms; the
+draft policy then picks longer windows (2.10 -> 2.31 tokens per window). Prompt reads are unchanged (437-438 tok/s at
+10.7K). `tools/q8_sm60_check.cu` checks the kernel against a CPU reference on these shapes (1-8 columns) and times it.
+
+Two things that mattered as much on this card: its default application clock is 759 MHz, and a layer split leaves
+each die idle most of a window, so the dies decode below 1050 MHz unless the clocks are locked
+(`nvidia-smi -i <dies> -ac 715,1050` as administrator; 25.0 -> 29.1 tok/s at 10.7K context). And a second engine on
+the same PC that pins its threads to the same logical CPUs halves this one's decode while it runs (the host thread
+is time-sliced); keeping the two on different logical CPUs (SMT siblings) avoided it.
+
A/B switches: `STRATA_DEQUANT_WIDE=0`, `STRATA_SM61_TABLE=0` (sm_61: the kernels 0.1.43.1 ran), `STRATA_DENSE_F32=1` (Pascal, opt-in),
-`STRATA_BF16_TC=0|1`, `STRATA_PROMPT_ATTN_OLD=1` (the decode kernel for prompts), `STRATA_ATTN_PRE75=0`
+`STRATA_Q8_SM60=0|1` (Pascal GP100, opt-in), `STRATA_BF16_TC=0|1`, `STRATA_PROMPT_ATTN_OLD=1` (the decode kernel for prompts), `STRATA_ATTN_PRE75=0`
(#540's kernel off; on gfx103x with HIP that kernel is the default, see the AMD table above, and `=1` turns it on for
another wave32 AMD card). [NVIDIA_V100.md](NVIDIA_V100.md) has the V100 build, its measurements and the parity test.
diff --git a/include/strata/kernels/native_mmvq.hpp b/include/strata/kernels/native_mmvq.hpp
index fef71027d..b9534ebfa 100644
--- a/include/strata/kernels/native_mmvq.hpp
+++ b/include/strata/kernels/native_mmvq.hpp
@@ -102,6 +102,11 @@ bool native_q8_0_packed_eligible(int n_in, int n_out);
void native_q8_0_pack_host(const void* gguf_blocks, void* out, int n_in, int n_out);
void native_q8_0_packed_register(const void* gguf_weights, const void* packed, int n_in, int n_out);
void native_q8_0_packed_unregister(const void* gguf_weights);
+/// STRATA_Q8_SM60=1 (opt-in, Pascal GP100): every Q8_0 dense matrix is packed as above whatever its shape, and the
+/// Q8_0 decode GEMVs run a kernel written for compute capability 6.0 (q8_sm60.cuh; not bitwise the exact kernels).
+/// native_q8_0_sm60_pack packs a device matrix here (the head) and owns the copy until native_q8_0_sm60_release.
+bool native_q8_0_sm60_pack(const void* weights, int n_in, int n_out, const char* what);
+void native_q8_0_sm60_release(const void* weights);
/// STRATA_Q6_PACKED=1 (opt-in): a packed copy of a Q6_K matrix (the output heads) - the same bytes as ql / qh /
/// scales / d planes - that native_q6_k_mmvq calls on `weights` read instead (bitwise equal outputs). The copy is
diff --git a/src/core/native_head.cpp b/src/core/native_head.cpp
index 8e239d3d6..a1fb19441 100644
--- a/src/core/native_head.cpp
+++ b/src/core/native_head.cpp
@@ -18,6 +18,7 @@ NativeHead::~NativeHead() {
void NativeHead::unload() {
if (weights_) strata::kernels::native_q6_k_unpack(weights_);
+ if (weights_) strata::kernels::native_q8_0_sm60_release(weights_);
if (scratch_) cudaFree(scratch_);
if (weights_) cudaFree(weights_);
scratch_ = nullptr;
@@ -73,6 +74,8 @@ bool NativeHead::load(const std::vector<std::string>& shards, int64_t n_in, int6
type_ = (int) tensor->type;
if (type_ == 14 && strata::kernels::native_q6_k_packed_enabled()) // STRATA_Q6_PACKED=1
strata::kernels::native_q6_k_pack(weights_, n_in_, n_out_, "output head");
+ if (type_ == 8) // STRATA_Q8_SM60=1 (a no-op otherwise); the MTP draft head reads the same matrix
+ strata::kernels::native_q8_0_sm60_pack(weights_, n_in_, n_out_, "output head");
return true;
} catch (const std::exception& error) {
err = std::string("native head: ") + error.what();
diff --git a/src/kernels/cuda/native_mmvq.cu b/src/kernels/cuda/native_mmvq.cu
index d537fd5fe..c83323d14 100644
--- a/src/kernels/cuda/native_mmvq.cu
+++ b/src/kernels/cuda/native_mmvq.cu
@@ -1726,6 +1726,25 @@ void small_f32(const void* weights, const float* x, void* scratch_q8_1,
small_mmvq<Weight, Qi>(weights, scratch_q8_1, y, n_in, n_out, ncols, stream);
}
+// STRATA_Q8_SM60=1 (opt-in, written for Pascal GP100): every Q8_0 dense matrix and the head get the packed planes
+// below and run q8sm60::kernel on them (q8_sm60.cuh) instead of the exact kernels.
+bool q8_sm60_on() {
+#if defined(__HIPCC__)
+ return false; // a CUDA kernel for one NVIDIA chip: HIP builds never compile it
+#else
+ static const bool on = [] {
+ const char* v = std::getenv("STRATA_Q8_SM60");
+ const bool yes = v && v[0] == '1' && v[1] == '\0';
+ if (yes) std::fprintf(stderr, "strata q8 sm60: Q8_0 decode GEMVs on the Pascal kernel (STRATA_Q8_SM60=1)\n");
+ return yes;
+ }();
+ return on;
+#endif
+}
+#if !defined(__HIPCC__)
+#include "q8_sm60.cuh"
+#endif
+
// ============================ STRATA_Q8_PACKED=1: the packed Q8_0 decode layout (opt-in) ============================
//
// A lossless load-time repack of a Q8_0 matrix: the SAME int8 values in a qs plane (row-major, n_in bytes per row)
@@ -1825,8 +1844,30 @@ void q8_packed_launch(const Q8Packed& w, const Q81Block* x, float* y, cudaStream
persist ? grid : w.n_out);
}
+bool q8_packed_shape(int n_in, int n_out) { // the shapes native_q8_0_packed_kernel was measured on
+ return n_in > 0 && n_in % 32 == 0 && n_in / 32 >= 2 * WARPS * WARP / 8 && n_in <= Q8P_PERSIST_MAX_IN &&
+ n_out >= 2048;
+}
+
bool q8_packed_mmvq(const void* weights, const void* x_q8_1, float* y, int n_in, int n_out, int ncols, void* stream) {
auto& registry = q8_packed_registry();
+#if !defined(__HIPCC__)
+ if (q8_sm60_on() && !registry.empty()) {
+ const auto found = registry.find(weights);
+ if (found != registry.end() && found->second.n_in == n_in && found->second.n_out == n_out) {
+ validate_pointer(x_q8_1);
+ validate_pointer(y);
+ validate_stream(stream);
+ if (q8sm60::launch(found->second.qs, found->second.d, static_cast<const Q81Block*>(x_q8_1), y, n_in,
+ n_out, ncols, static_cast<cudaStream_t>(stream))) {
+ launch_check();
+ return true;
+ }
+ // a shape the Pascal kernel declines: the exact packed kernel only where it was measured, else the GGUF layout
+ if (!q8_packed_shape(n_in, n_out)) return false;
+ }
+ }
+#endif
if (registry.empty() || (ncols > 1 && !g_multi_exact)) return false; // packed = the EXACT layout only
const auto found = registry.find(weights);
if (found == registry.end() || found->second.n_in != n_in || found->second.n_out != n_out) return false;
@@ -1992,12 +2033,61 @@ bool native_q8_0_packed_enabled() {
const char* v = std::getenv("STRATA_Q8_PACKED");
return v && v[0] == '1' && v[1] == '\0';
}();
- return enabled;
+ return enabled || q8_sm60_on();
}
bool native_q8_0_packed_eligible(int n_in, int n_out) {
- return n_in > 0 && n_in % 32 == 0 && n_in / 32 >= 2 * WARPS * WARP / 8 && n_in <= Q8P_PERSIST_MAX_IN &&
- n_out >= 2048;
+ if (q8_sm60_on()) return n_in >= 128 && n_in % 32 == 0 && n_out > 0; // the Pascal kernel takes any of them
+ return q8_packed_shape(n_in, n_out);
+}
+
+namespace {
+std::unordered_map<const void*, void*>& q8_sm60_owned() { // packed copies made here (the head), freed by release
+ static std::unordered_map<const void*, void*> owned;
+ return owned;
+}
+} // namespace
+
+bool native_q8_0_sm60_pack(const void* weights, int n_in, int n_out, const char* what) {
+#if defined(__HIPCC__)
+ (void) weights; (void) n_in; (void) n_out; (void) what;
+ return false;
+#else
+ if (!q8_sm60_on() || !weights || !native_q8_0_packed_eligible(n_in, n_out)) return false;
+ if (q8_packed_registry().count(weights)) return true;
+ const std::size_t count = std::size_t(n_in / 32) * std::size_t(n_out);
+ const std::size_t bytes = count * 34;
+ void* packed = nullptr;
+ if (cudaMalloc(&packed, bytes) != cudaSuccess) {
+ cudaGetLastError();
+ std::fprintf(stderr, "strata q8 sm60: no VRAM for the packed %s (%.0f MiB); it keeps the GGUF layout\n", what,
+ double(bytes) / 1048576.0);
+ return false;
+ }
+ auto* qs = static_cast<int8_t*>(packed);
+ auto* d = reinterpret_cast<half*>(qs + std::size_t(n_in) * n_out);
+ q8sm60::pack_kernel<<<unsigned((count + 255) / 256), 256>>>(static_cast<const Q80Block*>(weights), qs, d, count);
+ if (cudaDeviceSynchronize() != cudaSuccess) {
+ cudaGetLastError();
+ cudaFree(packed);
+ std::fprintf(stderr, "strata q8 sm60: packing the %s failed; it keeps the GGUF layout\n", what);
+ return false;
+ }
+ q8_packed_registry()[weights] = Q8Packed{qs, d, n_in, n_out};
+ q8_sm60_owned()[weights] = packed;
+ std::fprintf(stderr, "strata q8 sm60: packed %s (%d x %d, %.0f MiB more VRAM)\n", what, n_out, n_in,
+ double(bytes) / 1048576.0);
+ return true;
+#endif
+}
+
+void native_q8_0_sm60_release(const void* weights) {
+ auto& owned = q8_sm60_owned();
+ const auto it = owned.find(weights);
+ if (it == owned.end()) return;
+ q8_packed_registry().erase(weights);
+ cudaFree(it->second);
+ owned.erase(it);
}
void native_q8_0_pack_host(const void* gguf_blocks, void* out, int n_in, int n_out) {
diff --git a/src/kernels/cuda/q8_sm60.cuh b/src/kernels/cuda/q8_sm60.cuh
new file mode 100644
index 000000000..a45b84095
--- /dev/null
+++ b/src/kernels/cuda/q8_sm60.cuh
@@ -0,0 +1,148 @@
+// src/kernels/cuda/q8_sm60.cuh - a Q8_0 decode GEMV for Pascal GP100 (compute capability 6.0), opt-in with
+// STRATA_Q8_SM60=1. Included by native_mmvq.cu, and by a standalone parity/speed check, so both run this code.
+//
+// Reads the packed planes of STRATA_Q8_PACKED (the SAME int8 values row-major, n_in bytes per row, then one fp16 scale
+// per 32 of them) for every Q8_0 dense matrix and the head, whatever their shape. Why the packed kernel above is slow
+// on a GP100 die (measured on PH402, 1050 MHz: ~137 GB/s for the dense projections, ~160 for the head, against
+// 220-270 for this layout): one workgroup per row, eight bytes per thread per pass and a __syncthreads() per row - a
+// 2560-wide row is 80 blocks, so the reduction costs more than the row - and the window's activations read as single
+// ints, because a q8_1 block is 36 bytes and its values start at byte 4.
+//
+// Here:
+// * a workgroup first copies the window's activations into shared memory as an int8 plane per column and a float
+// scale per 32 (once; the workgroup then loops over rows), so every activation read is a 16-byte shared load;
+// * TPR threads own a row (a whole warp for n_in >= 2048, a half or a quarter for narrower rows) and read its
+// weights 16 bytes at a time through the read-only cache; the dot of 4 ints is STRATA_DP4A (vmad on sm_60);
+// * the sum is a shuffle within those TPR lanes - no shared memory, no barrier per row.
+// The per-32 products are added in another order than the exact kernels', so outputs are not bitwise theirs (float
+// rounding only; the int8 dots are exact).
+#pragma once
+
+namespace q8sm60 {
+
+constexpr int THREADS = 256;
+constexpr std::size_t MAX_SMEM = 48 * 1024; // a Pascal workgroup's static + dynamic limit
+
+inline std::size_t smem_bytes(int ncols, int n_in) {
+ return std::size_t(ncols) * std::size_t(n_in) + std::size_t(ncols) * std::size_t(n_in / 32) * sizeof(float);
+}
+
+template<int NCOLS, int TPR>
+__launch_bounds__(THREADS)
+__global__ void kernel(const int8_t* __restrict__ qs, const half* __restrict__ dpl, const Q81Block* __restrict__ x,
+ float* __restrict__ y, int n_in, int n_out) {
+ extern __shared__ int4 q8sm60_smem[];
+ int8_t* sx = reinterpret_cast<int8_t*>(q8sm60_smem); // [NCOLS][n_in]
+ float* sd = reinterpret_cast<float*>(sx + std::size_t(NCOLS) * n_in); // [NCOLS][n_in / 32]
+ const int nb = n_in / 32;
+ for (int b = int(threadIdx.x); b < NCOLS * nb; b += THREADS) { // column j = b / nb, block b % nb
+ const Q81Block* xb = x + b;
+ const int* src = reinterpret_cast<const int*>(xb->qs);
+ int* dst = reinterpret_cast<int*>(sx + std::size_t(b) * 32);
+#pragma unroll
+ for (int i = 0; i < 8; ++i) dst[i] = src[i];
+ sd[b] = __low2float(xb->ds);
+ }
+ __syncthreads();
+
+ constexpr int RPB = THREADS / TPR;
+ const int lane = int(threadIdx.x) % TPR;
+ const int rloc = int(threadIdx.x) / TPR;
+ const int nch = n_in / 16; // 16-byte chunks, two per block
+ const int groups = (n_out + RPB - 1) / RPB;
+ for (int g = int(blockIdx.x); g < groups; g += int(gridDim.x)) {
+ const int row = g * RPB + rloc;
+ float acc[NCOLS];
+#pragma unroll
+ for (int j = 0; j < NCOLS; ++j) acc[j] = 0.0f;
+ if (row < n_out) {
+ const int4* w = reinterpret_cast<const int4*>(qs + std::size_t(row) * n_in);
+ const half* d = dpl + std::size_t(row) * nb;
+ for (int c = lane; c < nch; c += TPR) {
+ const int4 wv = __ldg(w + c);
+ const float dw = __half2float(d[c >> 1]);
+#pragma unroll
+ for (int j = 0; j < NCOLS; ++j) {
+ const int4 xv = reinterpret_cast<const int4*>(sx + std::size_t(j) * n_in)[c];
+ int s = STRATA_DP4A(wv.x, xv.x, 0);
+ s = STRATA_DP4A(wv.y, xv.y, s);
+ s = STRATA_DP4A(wv.z, xv.z, s);
+ s = STRATA_DP4A(wv.w, xv.w, s);
+ acc[j] += dw * sd[j * nb + (c >> 1)] * float(s);
+ }
+ }
+ }
+#pragma unroll
+ for (int j = 0; j < NCOLS; ++j) { // every lane takes part, row or not
+ float v = acc[j];
+#pragma unroll
+ for (int o = TPR / 2; o > 0; o >>= 1) v += __shfl_xor_sync(0xffffffffu, v, o, TPR);
+ if (lane == 0 && row < n_out) y[std::size_t(j) * n_out + row] = v;
+ }
+ }
+}
+
+// One workgroup per SM would leave too few rows in flight on a 48-SM die; four per SM is what the shapes of
+// Qwen3.8-Flash-Next measured best (STRATA_Q8_SM60_BPS overrides it).
+inline int blocks_per_sm() {
+ static const int v = [] {
+ const char* e = std::getenv("STRATA_Q8_SM60_BPS");
+ const int n = e ? std::atoi(e) : 0;
+ return n > 0 ? n : 4;
+ }();
+ return v;
+}
+
+inline int sm_count() {
+ int dev = 0, n = 0;
+ if (cudaGetDevice(&dev) != cudaSuccess || cudaDeviceGetAttribute(&n, cudaDevAttrMultiProcessorCount, dev) != cudaSuccess)
+ return 48;
+ return n > 0 ? n : 48;
+}
+
+template<int NCOLS, int TPR>
+void launch_one(const int8_t* qs, const half* d, const Q81Block* x, float* y, int n_in, int n_out, cudaStream_t s) {
+ constexpr int RPB = THREADS / TPR;
+ const int groups = (n_out + RPB - 1) / RPB;
+ const int grid = (std::min)(groups, sm_count() * blocks_per_sm());
+ kernel<NCOLS, TPR><<<unsigned(grid), THREADS, smem_bytes(NCOLS, n_in), s>>>(qs, d, x, y, n_in, n_out);
+}
+
+template<int NCOLS>
+void launch_cols(const int8_t* qs, const half* d, const Q81Block* x, float* y, int n_in, int n_out, cudaStream_t s) {
+ if (n_in >= 2048) launch_one<NCOLS, 32>(qs, d, x, y, n_in, n_out, s);
+ else if (n_in >= 1024) launch_one<NCOLS, 16>(qs, d, x, y, n_in, n_out, s);
+ else launch_one<NCOLS, 8>(qs, d, x, y, n_in, n_out, s);
+}
+
+// false: a shape this kernel does not take (the caller runs its usual kernel)
+inline bool launch(const int8_t* qs, const half* d, const Q81Block* x, float* y, int n_in, int n_out, int ncols,
+ cudaStream_t s) {
+ if (n_in % 32 != 0 || n_in < 128 || ncols < 1 || ncols > 8 || smem_bytes(ncols, n_in) > MAX_SMEM) return false;
+ switch (ncols) {
+ case 1: launch_cols<1>(qs, d, x, y, n_in, n_out, s); break;
+ case 2: launch_cols<2>(qs, d, x, y, n_in, n_out, s); break;
+ case 3: launch_cols<3>(qs, d, x, y, n_in, n_out, s); break;
+ case 4: launch_cols<4>(qs, d, x, y, n_in, n_out, s); break;
+ case 5: launch_cols<5>(qs, d, x, y, n_in, n_out, s); break;
+ case 6: launch_cols<6>(qs, d, x, y, n_in, n_out, s); break;
+ case 7: launch_cols<7>(qs, d, x, y, n_in, n_out, s); break;
+ default: launch_cols<8>(qs, d, x, y, n_in, n_out, s); break;
+ }
+ return true;
+}
+
+// GGUF Q8_0 blocks (34 bytes, 2-byte aligned) -> the packed planes, on the device (the head's 0.6 GiB stays off the host)
+__global__ void pack_kernel(const Q80Block* __restrict__ blocks, int8_t* __restrict__ qs, half* __restrict__ d,
+ std::size_t count) {
+ const std::size_t b = std::size_t(blockIdx.x) * blockDim.x + threadIdx.x;
+ if (b >= count) return;
+ const Q80Block& src = blocks[b];
+ const uint16_t* in = reinterpret_cast<const uint16_t*>(src.qs);
+ uint16_t* out = reinterpret_cast<uint16_t*>(qs + b * 32);
+#pragma unroll
+ for (int i = 0; i < 16; ++i) out[i] = in[i];
+ d[b] = src.d;
+}
+
+} // namespace q8sm60
diff --git a/tools/q8_dense_gguf.py b/tools/q8_dense_gguf.py
new file mode 100644
index 000000000..e094cd32a
--- /dev/null
+++ b/tools/q8_dense_gguf.py
@@ -0,0 +1,146 @@
+"""tools/q8_dense_gguf.py - a copy of a model's first shard whose natively served dense projections and head are Q8_0,
+for the Pascal GP100 decode kernel (STRATA_Q8_SM60=1, docs/OLDER_GPUS.md).
+
+The GSQ-RCO packs keep those matrices in K- and i-quants (Q6_K, IQ4_XS, Q4_K, IQ3_S, Q5_K, Q2_0, IQ4_NL), whose
+decode is what a GP100 die is slowest at; STRATA_Q8_SM60 only runs Q8_0 matrices. This writes:
+
+ * the tensor-info block with the SAME byte length: names and dims are unchanged, only the u32 type and the u64
+ offset of each converted tensor change, so the data section starts where it did and every other tensor - the
+ routed experts above all - keeps its absolute offset. An existing native pack (its native_experts.txt) stays
+ valid; nothing is repacked.
+ * the original data section, then each converted tensor's Q8_0 blocks appended (the old bytes stay, unused).
+ Qwen3.8-Flash-Next IQ3_XXS: 301 tensors, +3.5 GiB, the worst requantization error 0.41% of a tensor's |w|max
+ (Q8_0 is finer than every source format).
+
+The other shards of the model are hard-linked into the output folder (--copy copies them): the engine finds them
+beside --native, so --ple-gguf must name the one in the new folder too (it refuses two shard 2s).
+
+ python tools/q8_dense_gguf.py <folder>/<model>-00001-of-00002.gguf <new folder> [--copy]
+
+Then point the config's --native and --ple-gguf at the new folder and run the engine with STRATA_Q8_SM60=1.
+"""
+from __future__ import annotations
+
+import argparse
+import os
+import re
+import shutil
+import struct
+import sys
+import time
+from pathlib import Path
+
+import numpy as np
+
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+import _paths # noqa: E402
+
+_paths.add_gguf_py()
+from gguf import GGUFReader, GGMLQuantizationType as QT # noqa: E402
+from gguf.quants import dequantize, quantize # noqa: E402
+from gguf_writer import dequantize_q2_0 # noqa: E402
+
+# what src/core/native_dense.cpp serves natively (eligible()), and the head
+SUFFIXES = (".attn_qkv.weight", ".attn_gate.weight", ".ssm_out.weight", ".attn_q.weight", ".attn_k.weight",
+ ".attn_v.weight", ".attn_output.weight", ".ffn_gate_shexp.weight", ".ffn_up_shexp.weight",
+ ".ffn_down_shexp.weight")
+Q2_0 = 42 # GSQ's 2-bit type: gguf-py has no member for it
+
+
+def is_target(name: str) -> bool:
+ return name == "output.weight" or (name.startswith("blk.") and name.endswith(SUFFIXES))
+
+
+def to_f32(t) -> np.ndarray:
+ ne0, ne1 = int(t.shape[0]), int(t.shape[1])
+ raw = np.asarray(t.data)
+ if int(t.tensor_type) == Q2_0:
+ return np.asarray(dequantize_q2_0(raw.tobytes()), dtype=np.float32).reshape(ne1, ne0)
+ return np.asarray(dequantize(raw, t.tensor_type), dtype=np.float32).reshape(ne1, ne0)
+
+
+def main() -> int:
+ ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
+ ap.add_argument("shard1", type=Path, help="the model's first GGUF shard (the one --native names)")
+ ap.add_argument("out_dir", type=Path, help="folder for the new shard 1 and the other shards' links")
+ ap.add_argument("--copy", action="store_true", help="copy the other shards instead of hard-linking them")
+ a = ap.parse_args()
+ src = a.shard1.resolve()
+ out = a.out_dir.resolve()
+ if out == src.parent:
+ sys.exit("the output folder must not be the model's own folder")
+ dst = out / src.name
+
+ t0 = time.time()
+ r = GGUFReader(src)
+ align, data_start, src_size = r.alignment, r.data_offset, os.path.getsize(src)
+ mm = r.data
+ jobs = []
+ for t in r.tensors:
+ if not is_target(t.name) or int(t.tensor_type) == int(QT.Q8_0):
+ continue
+ p = t.field.offset # the tensor-info entry: name, n_dims, dims, type, offset
+ nlen = struct.unpack_from("<Q", mm, p)[0]; p += 8
+ assert bytes(mm[p:p + nlen]).decode() == t.name; p += nlen
+ ndim = struct.unpack_from("<I", mm, p)[0]; p += 4 + 8 * ndim
+ ttype, toff = struct.unpack_from("<IQ", mm, p)
+ assert ttype == int(t.tensor_type) and data_start + toff == t.data_offset, t.name
+ if int(t.shape[0]) % 32:
+ print(f" {t.name}: rows of {int(t.shape[0])} are not whole Q8_0 blocks, kept")
+ continue
+ jobs.append((t, p))
+ print(f"{src.name}: {len(r.tensors)} tensors, {len(jobs)} to convert to Q8_0", flush=True)
+
+ blobs, worst = [], 0.0
+ for t, p in jobs:
+ f = to_f32(t)
+ q = np.ascontiguousarray(quantize(f, QT.Q8_0)).view(np.uint8).reshape(-1)
+ assert q.nbytes == int(t.shape[0]) // 32 * 34 * int(t.shape[1]), t.name
+ back = dequantize(q, QT.Q8_0).reshape(f.shape)
+ worst = max(worst, float(np.abs(back - f).max() / max(float(np.abs(f).max()), 1e-30)))
+ blobs.append((t, p, q))
+ print(f"converted in {time.time() - t0:.0f} s; worst requantization error {worst:.2e} of a tensor's |w|max; "
+ f"{sum(b[2].nbytes for b in blobs) / 2**30:.2f} GiB to append", flush=True)
+
+ out.mkdir(parents=True, exist_ok=True)
+ tmp = dst.with_name(dst.name + ".part")
+ shutil.copyfile(src, tmp)
+ with open(tmp, "r+b") as fh:
+ end = src_size
+ for t, p, blob in blobs:
+ at = (end + align - 1) // align * align
+ fh.seek(end); fh.write(b"\0" * (at - end))
+ fh.seek(at); fh.write(blob.tobytes())
+ end = at + blob.nbytes
+ fh.seek(p); fh.write(struct.pack("<IQ", int(QT.Q8_0), at - data_start))
+ fh.flush(); os.fsync(fh.fileno())
+ os.replace(tmp, dst)
+
+ v = GGUFReader(dst) # every other tensor where it was, every new one as written
+ conv = {t.name: blob for t, _, blob in blobs}
+ orig = {t.name: t for t in r.tensors}
+ assert len(v.tensors) == len(r.tensors) and v.data_offset == data_start
+ for t in v.tensors:
+ if t.name in conv:
+ assert t.tensor_type == QT.Q8_0 and np.array_equal(np.asarray(t.data).view(np.uint8).reshape(-1), conv[t.name]), t.name
+ else:
+ assert t.tensor_type == orig[t.name].tensor_type and t.data_offset == orig[t.name].data_offset, t.name
+ print(f"wrote {dst} ({os.path.getsize(dst) / 2**30:.2f} GiB): {len(conv)} converted, {len(v.tensors) - len(conv)} "
+ "untouched, offsets checked", flush=True)
+
+ m = re.match(r"(.*-)(\d{5})-of-(\d{5})(\.gguf)$", src.name)
+ if m:
+ for k in range(1, int(m[3]) + 1):
+ name = f"{m[1]}{k:05d}-of-{m[3]}{m[4]}"
+ if k == int(m[2]) or (out / name).exists():
+ continue
+ if a.copy:
+ shutil.copyfile(src.parent / name, out / name)
+ else:
+ os.link(src.parent / name, out / name)
+ print(f"{'copied' if a.copy else 'linked'} {name}")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/tools/q8_sm60_check.cu b/tools/q8_sm60_check.cu
new file mode 100644
index 000000000..b1435af20
--- /dev/null
+++ b/tools/q8_sm60_check.cu
@@ -0,0 +1,108 @@
+// tools/q8_sm60_check.cu - parity and speed of the STRATA_Q8_SM60=1 kernel (src/kernels/cuda/q8_sm60.cuh) on the
+// Q8_0 shapes of Qwen3.8-Flash-Next (hidden 2560): the dense projections, the shared expert and the head.
+//
+// It includes the committed header, so the check covers the code the engine compiles, not a copy. Parity: random
+// Q8_0 weights in GGUF blocks -> q8sm60::pack_kernel -> the kernel, against a CPU double reference of
+// sum over blocks of d_w * d_x * dot_int8, for 1..8 columns (max relative error < 1e-5). Speed: a 1 GiB rotation so
+// the weights come from DRAM, as in the engine. No CMake target; build by hand:
+//
+// nvcc -O3 -arch=sm_60 -std=c++17 -Iinclude -Isrc/kernels/cuda tools/q8_sm60_check.cu -o q8_sm60_check && ./q8_sm60_check
+//
+// Exit status 0 = every case within tolerance and no CUDA error.
+#include <cuda_fp16.h>
+#include <cuda_runtime.h>
+#include <algorithm>
+#include <cmath>
+#include <cstdint>
+#include <cstdio>
+#include <cstdlib>
+#include <cstring>
+#include <vector>
+#define CK(x) do { cudaError_t e_ = (x); if (e_ != cudaSuccess) { printf("CUDA %s at %d\n", cudaGetErrorString(e_), __LINE__); exit(1); } } while (0)
+struct Q81Block { half2 ds; int8_t qs[32]; };
+struct Q80Block { half d; int8_t qs[32]; };
+#include "strata/kernels/dp4a.hpp"
+#include "q8_sm60.cuh"
+
+static float h2f(half h) { return __half2float(h); }
+
+static bool parity(int n_in, int n_out, int ncols) {
+ const int nb = n_in / 32;
+ std::vector<Q80Block> w((size_t) n_out * nb);
+ std::vector<Q81Block> x((size_t) ncols * nb);
+ srand(n_in * 7 + n_out + ncols);
+ for (auto& b : w) { b.d = __float2half((rand() % 1000 + 1) * 1e-5f); for (auto& q : b.qs) q = (int8_t) (rand() % 255 - 127); }
+ for (auto& b : x) { b.ds = __halves2half2(__float2half((rand() % 1000 + 1) * 1e-4f), __float2half(0.f)); for (auto& q : b.qs) q = (int8_t) (rand() % 255 - 127); }
+ std::vector<double> ref((size_t) ncols * n_out);
+ for (int j = 0; j < ncols; ++j) for (int r = 0; r < n_out; ++r) {
+ double s = 0;
+ for (int b = 0; b < nb; ++b) {
+ const Q80Block& wb = w[(size_t) r * nb + b]; const Q81Block& xb = x[(size_t) j * nb + b];
+ int dot = 0; for (int i = 0; i < 32; ++i) dot += wb.qs[i] * xb.qs[i];
+ s += (double) h2f(wb.d) * __low2float(xb.ds) * dot;
+ }
+ ref[(size_t) j * n_out + r] = s;
+ }
+ Q80Block* dw; Q81Block* dx; float* dy; int8_t* qs;
+ CK(cudaMalloc(&dw, w.size() * sizeof(Q80Block))); CK(cudaMemcpy(dw, w.data(), w.size() * sizeof(Q80Block), cudaMemcpyHostToDevice));
+ CK(cudaMalloc(&dx, x.size() * sizeof(Q81Block))); CK(cudaMemcpy(dx, x.data(), x.size() * sizeof(Q81Block), cudaMemcpyHostToDevice));
+ CK(cudaMalloc(&dy, ref.size() * 4)); CK(cudaMemset(dy, 0xff, ref.size() * 4));
+ const size_t count = (size_t) n_out * nb;
+ CK(cudaMalloc(&qs, count * 34));
+ half* d = reinterpret_cast<half*>(qs + (size_t) n_in * n_out);
+ q8sm60::pack_kernel<<<unsigned((count + 255) / 256), 256>>>(dw, qs, d, count);
+ const bool took = q8sm60::launch(qs, d, dx, dy, n_in, n_out, ncols, 0);
+ CK(cudaDeviceSynchronize());
+ bool ok = true;
+ if (took) {
+ std::vector<float> y(ref.size()); CK(cudaMemcpy(y.data(), dy, y.size() * 4, cudaMemcpyDeviceToHost));
+ double m = 0, e = 0; for (size_t i = 0; i < y.size(); ++i) { m = std::max(m, std::fabs(ref[i])); e = std::max(e, std::fabs(y[i] - ref[i])); }
+ ok = e / m < 1e-5 && std::isfinite(e);
+ if (!ok) printf(" FAIL %d -> %d, %d cols: max rel err %.2e\n", n_in, n_out, ncols, e / m);
+ }
+ cudaFree(dw); cudaFree(dx); cudaFree(dy); cudaFree(qs);
+ return ok;
+}
+
+int main() {
+ cudaDeviceProp p; CK(cudaGetDeviceProperties(&p, 0));
+ printf("%s, %d SMs, %d MHz\n", p.name, p.multiProcessorCount, p.clockRate / 1000);
+ struct S { const char* name; int n_in, n_out; } shapes[] = {
+ {"gdn attn_qkv", 2560, 10240}, {"gdn attn_gate", 2560, 6144}, {"ssm_out / attn_output", 6144, 2560},
+ {"qsa attn_q", 2560, 12288}, {"qsa attn_k / v", 2560, 512}, {"shexp gate / up", 2560, 640},
+ {"shexp down", 640, 2560}, {"head", 2560, 248320}};
+ bool ok = true; int checked = 0, declined = 0;
+ for (const S& s : shapes) for (int c = 1; c <= 8; ++c) {
+ if (s.n_out > 20000 && c > 2) continue; // the head's CPU reference is slow; 1-2 columns cover its path
+ if (q8sm60::smem_bytes(c, s.n_in) > q8sm60::MAX_SMEM) { ++declined; continue; }
+ ok = parity(s.n_in, s.n_out, c) && ok; ++checked;
+ }
+ printf("parity: %d shape x column cases %s (%d declined: shared memory)\n\n", checked, ok ? "PASS (max rel err < 1e-5)" : "FAIL", declined);
+ if (!ok) return 1;
+
+ const size_t POOL = 1ull << 30;
+ int8_t* pool; CK(cudaMalloc(&pool, POOL)); CK(cudaMemset(pool, 1, POOL));
+ Q81Block* dx; CK(cudaMalloc(&dx, 8 * (6144 / 32) * sizeof(Q81Block))); CK(cudaMemset(dx, 0, 8 * (6144 / 32) * sizeof(Q81Block)));
+ float* dy; CK(cudaMalloc(&dy, (size_t) 8 * 248320 * 4));
+ int8_t* head; const size_t head_bytes = (size_t) 248320 * 2560 / 32 * 34; CK(cudaMalloc(&head, head_bytes)); CK(cudaMemset(head, 0, head_bytes));
+ cudaEvent_t a, b; CK(cudaEventCreate(&a)); CK(cudaEventCreate(&b));
+ printf("%-22s %6s %7s |", "matrix", "n_in", "n_out"); for (int c = 1; c <= 6; ++c) printf(" T=%d us GB/s", c); printf("\n");
+ for (const S& s : shapes) {
+ printf("%-22s %6d %7d |", s.name, s.n_in, s.n_out);
+ const size_t bytes = (size_t) s.n_in / 32 * 34 * s.n_out;
+ for (int c = 1; c <= 6; ++c) {
+ if (q8sm60::smem_bytes(c, s.n_in) > q8sm60::MAX_SMEM) { printf(" %14s", "-"); continue; }
+ const int iters = s.n_out > 20000 ? 10 : 100;
+ auto at = [&](int i) -> int8_t* { if (s.n_out > 20000) return head; const size_t span = (POOL - bytes) / 256;
+ return pool + ((size_t) i * ((bytes + 255) / 256) % span) * 256; };
+ for (int i = 0; i < 3; ++i) { int8_t* q = at(i); q8sm60::launch(q, (half*) (q + (size_t) s.n_in * s.n_out), dx, dy, s.n_in, s.n_out, c, 0); }
+ CK(cudaEventRecord(a));
+ for (int i = 0; i < iters; ++i) { int8_t* q = at(i + 3); q8sm60::launch(q, (half*) (q + (size_t) s.n_in * s.n_out), dx, dy, s.n_in, s.n_out, c, 0); }
+ CK(cudaEventRecord(b)); CK(cudaEventSynchronize(b));
+ float ms; CK(cudaEventElapsedTime(&ms, a, b)); const double us = ms * 1000.0 / iters;
+ printf(" %7.1f %6.0f", us, bytes / (us * 1e3));
+ }
+ printf("\n");
+ }
+ return 0;
+}