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++

dsv41 cudalab: trellis K4-K7 dequant + GEMV v1 on sm_86 with parity and speed harness (tqenc and the K5/K4 CPU decoder taken from f-dsv41-enc)

Niko1221090121c31be9
diff --git a/include/strata/kernels/cpu/tq_cpu.hpp b/include/strata/kernels/cpu/tq_cpu.hpp
index 132cb99e1..a73e300e8 100644
--- a/include/strata/kernels/cpu/tq_cpu.hpp
+++ b/include/strata/kernels/cpu/tq_cpu.hpp
@@ -31,11 +31,16 @@ namespace strata::kernels::cpu {
enum class TqIsa : int { scalar = 0, avx2 = 1, avx512 = 2 };
-/// TQ2_T (144), TQK6 (145), TQK7 (146).
+/// EXPERIMENTAL lower-rate versions of the TQK rule (tools/trellis/tqenc.hpp, version 1; Strata-internal ids, not ggml
+/// types, not in any GGUF): TQK5X = 22 bytes / 128 weights (1.375 bpw), TQK4X = 18 bytes (1.125 bpw). Same hash,
+/// codebook, 15-bit mask, LSB-first circular stream and fp16 scale as TQK6/7 with K = 5 / 4.
+inline constexpr int kTqTypeK5X = 224;
+inline constexpr int kTqTypeK4X = 225;
+/// TQ2_T (144), TQK6 (145), TQK7 (146) and the experimental TQK5X / TQK4X.
bool tq_supported(int ggml_type) noexcept;
-/// Bits per step: 8, 6, 7 (0 for any other type).
+/// Bits per step: 8, 6, 7, 5, 4 (0 for any other type).
int tq_kbits(int ggml_type) noexcept;
-/// Values per block of the trellis types, and bytes per block (2 + 4 * bits: 34, 26, 30).
+/// Values per block of the trellis types, and bytes per block (2 + 4 * bits: 34, 26, 30, 22, 18).
constexpr int kTqBlock = 128;
inline size_t tq_block_bytes(int ggml_type) noexcept { return (size_t) (2 + 4 * tq_kbits(ggml_type)); }
/// The best ISA this CPU runs (capped by STRATA_TQ_ISA).
diff --git a/src/kernels/cpu/tq_avx2.cpp b/src/kernels/cpu/tq_avx2.cpp
index 00918edf6..f03892510 100644
--- a/src/kernels/cpu/tq_avx2.cpp
+++ b/src/kernels/cpu/tq_avx2.cpp
@@ -81,6 +81,8 @@ void tq_rows_avx2(int kb, const uint8_t* w, size_t row_bytes, int n, const TqAct
float* const* out, int r0, int r1) {
if (kb == 8) rows_t<8>(w, row_bytes, n, a, nt, out, r0, r1);
else if (kb == 6) rows_t<6>(w, row_bytes, n, a, nt, out, r0, r1);
+ else if (kb == 5) rows_t<5>(w, row_bytes, n, a, nt, out, r0, r1); // experimental TQK5X
+ else if (kb == 4) rows_t<4>(w, row_bytes, n, a, nt, out, r0, r1); // experimental TQK4X
else rows_t<7>(w, row_bytes, n, a, nt, out, r0, r1);
}
diff --git a/src/kernels/cpu/tq_avx512.cpp b/src/kernels/cpu/tq_avx512.cpp
index b45118844..9031b8cf5 100644
--- a/src/kernels/cpu/tq_avx512.cpp
+++ b/src/kernels/cpu/tq_avx512.cpp
@@ -89,6 +89,8 @@ void tq_rows_avx512(int kb, const uint8_t* w, size_t row_bytes, int n, const TqA
float* const* out, int r0, int r1) {
if (kb == 8) rows_t<8>(w, row_bytes, n, a, nt, out, r0, r1);
else if (kb == 6) rows_t<6>(w, row_bytes, n, a, nt, out, r0, r1);
+ else if (kb == 5) rows_t<5>(w, row_bytes, n, a, nt, out, r0, r1); // experimental TQK5X
+ else if (kb == 4) rows_t<4>(w, row_bytes, n, a, nt, out, r0, r1); // experimental TQK4X
else rows_t<7>(w, row_bytes, n, a, nt, out, r0, r1);
}
diff --git a/src/kernels/cpu/tq_cpu.cpp b/src/kernels/cpu/tq_cpu.cpp
index 1240d7f74..ad7ea297d 100644
--- a/src/kernels/cpu/tq_cpu.cpp
+++ b/src/kernels/cpu/tq_cpu.cpp
@@ -89,9 +89,11 @@ const int16_t* tq_state_table() {
return g_table;
}
-bool tq_supported(int t) noexcept { return t == 144 || t == 145 || t == 146; }
+bool tq_supported(int t) noexcept { return t == 144 || t == 145 || t == 146 || t == kTqTypeK5X || t == kTqTypeK4X; }
-int tq_kbits(int t) noexcept { return t == 144 ? 8 : t == 145 ? 6 : t == 146 ? 7 : 0; }
+int tq_kbits(int t) noexcept {
+ return t == 144 ? 8 : t == 145 ? 6 : t == 146 ? 7 : t == kTqTypeK5X ? 5 : t == kTqTypeK4X ? 4 : 0;
+}
bool tq_isa_ok(TqIsa isa) {
#if defined(STRATA_TQ_X86)
@@ -144,6 +146,8 @@ void tq_rows_scalar(int kb, const uint8_t* w, size_t row_bytes, int n, const TqA
float* const* out, int r0, int r1) {
if (kb == 8) rows_scalar_t<8>(w, row_bytes, n, a, nt, out, r0, r1);
else if (kb == 6) rows_scalar_t<6>(w, row_bytes, n, a, nt, out, r0, r1);
+ else if (kb == 5) rows_scalar_t<5>(w, row_bytes, n, a, nt, out, r0, r1); // experimental TQK5X
+ else if (kb == 4) rows_scalar_t<4>(w, row_bytes, n, a, nt, out, r0, r1); // experimental TQK4X
else rows_scalar_t<7>(w, row_bytes, n, a, nt, out, r0, r1);
}
diff --git a/tools/dsv41_lab/build.sh b/tools/dsv41_lab/build.sh
new file mode 100644
index 000000000..7b7f1b980
--- /dev/null
+++ b/tools/dsv41_lab/build.sh
@@ -0,0 +1,9 @@
+#!/bin/bash
+# build the trellis kernel lab on a CUDA box: tools/dsv41_lab/build.sh [arch, default sm_86]
+set -e
+cd "$(dirname "$0")"
+ARCH=${1:-sm_86}
+NVCC=${NVCC:-/usr/local/cuda-12.9/bin/nvcc}
+mkdir -p out
+g++ -O2 -std=c++17 -I../../third_party/ggml -c ../trellis/tqenc.cpp -o out/tqenc.o
+$NVCC -O3 -std=c++17 -arch=$ARCH -lineinfo -o out/tqk_lab tqk_lab.cu out/tqenc.o -lpthread
diff --git a/tools/dsv41_lab/tqk_gemv.cuh b/tools/dsv41_lab/tqk_gemv.cuh
new file mode 100644
index 000000000..4ffab23b7
--- /dev/null
+++ b/tools/dsv41_lab/tqk_gemv.cuh
@@ -0,0 +1,141 @@
+// tools/dsv41_lab/tqk_gemv.cuh - CUDA GEMV / small-batch GEMM kernels for the trellis expert formats at DeepSeek shapes
+// (TQK4X/5X = types 225/224 of f-dsv41-enc, TQK6/7 = ggml 145/146), weights stay in the file layout:
+// row = nblk blocks of {fp16 d; 4K stream bytes}, block = 128 weights = 32 steps of 4; step t's 15-bit state is the
+// stream window at bit (31-t)*K (LSB first, circular); w = d * codebook(state); codebook = int16 table / 8192 (the
+// CPU decoder's table: tqenc::point_table()).
+// Plain C++ in the kernels (no inline PTX, no tensor-core intrinsics) so the HIP port is a rename.
+#pragma once
+#include <cstdint>
+#include <cuda_fp16.h>
+#include <cuda_runtime.h>
+
+namespace tqlab {
+
+constexpr uint32_t kMask = 0x7fffu;
+constexpr uint32_t kHash = 0x9e3779b1u;
+
+template <int K> struct Fmt {
+ static constexpr int kBits = K;
+ static constexpr int kBlockBytes = 2 + 4 * K;
+ static constexpr int kWords = 2 * K; // u16 words of the stream
+};
+
+// One job = one matrix (rows x in) applied to NB columns of activations (F32, [col][in]) -> Y[col][rows].
+struct Job {
+ const uint8_t* w; // rows * row_bytes, row_bytes = in / 128 * block bytes (2-byte aligned)
+ const float* x; // [NB][ldx]
+ float* y; // [NB][ldy]
+ int rows;
+ int ldx, ldy;
+};
+
+// the four unscaled weights of the step with state s from the float2 point table
+__device__ __forceinline__ void step_w(const float2* __restrict__ lut, uint32_t s, float2& a, float2& b) {
+ const uint32_t x = (s & kMask) * kHash;
+ a = lut[x >> 21];
+ b = lut[(x >> 10) & 2047u];
+}
+
+// the 4 states of steps 4l..4l+3 of a block whose stream starts at qs (2-byte aligned)
+template <int K>
+__device__ __forceinline__ void states4(const uint16_t* __restrict__ qs, int l, uint32_t s[4]) {
+ constexpr int nwords = 2 * K;
+ const int off3 = (28 - 4 * l) * K, wb = off3 >> 4, r = off3 & 15;
+ const int i1 = wb + 1 >= nwords ? wb + 1 - nwords : wb + 1;
+ const int i2 = wb + 2 >= nwords ? wb + 2 - nwords : wb + 2;
+ const int i3 = wb + 3 >= nwords ? wb + 3 - nwords : wb + 3;
+ const uint64_t v = (uint64_t) qs[wb] | ((uint64_t) qs[i1] << 16) | ((uint64_t) qs[i2] << 32) | ((uint64_t) qs[i3] << 48);
+#pragma unroll
+ for (int i = 0; i < 4; ++i) s[i] = (uint32_t) (v >> (r + (3 - i) * K)) & kMask;
+}
+
+// ------------------------------------------------------------------------------------------------------------
+// v1: warp per RPW rows, lane = 16-weight unit (4 steps), 32 units = 4 blocks per iteration. F32 activations from
+// global/L1, point table in shared memory as float2.
+template <int K, int NB, int RPW>
+__global__ void __launch_bounds__(256) gemv_v1(const Job* __restrict__ jobs, const float2* __restrict__ lut_g, int in) {
+ __shared__ float2 lut[2048];
+ for (int i = threadIdx.x; i < 2048; i += blockDim.x) lut[i] = lut_g[i];
+ __syncthreads();
+ const Job job = jobs[blockIdx.y];
+ const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31;
+ const int row0 = (blockIdx.x * (blockDim.x >> 5) + warp) * RPW;
+ if (row0 >= job.rows) return;
+ constexpr int bsz = Fmt<K>::kBlockBytes;
+ const int nblk = in / 128;
+ const size_t row_bytes = (size_t) nblk * bsz;
+ float acc[RPW][NB];
+#pragma unroll
+ for (int r = 0; r < RPW; ++r)
+#pragma unroll
+ for (int c = 0; c < NB; ++c) acc[r][c] = 0.f;
+ const int l = lane & 7, bsub = lane >> 3; // unit lane in block, block within the group of 4
+ for (int b0 = 0; b0 < nblk; b0 += 4) {
+ const int b = b0 + bsub;
+ if (b >= nblk) break;
+ float4 xv[NB][4];
+#pragma unroll
+ for (int c = 0; c < NB; ++c) {
+ const float4* xp = (const float4*) (job.x + (size_t) c * job.ldx + b * 128 + 16 * l);
+#pragma unroll
+ for (int i = 0; i < 4; ++i) xv[c][i] = __ldg(xp + i);
+ }
+#pragma unroll
+ for (int r = 0; r < RPW; ++r) {
+ const int row = row0 + r;
+ if (row >= job.rows) continue;
+ const uint8_t* blk = job.w + (size_t) row * row_bytes + (size_t) b * bsz;
+ const float d = __half2float(__ushort_as_half(*(const uint16_t*) blk));
+ uint32_t s[4];
+ states4<K>((const uint16_t*) (blk + 2), l, s);
+ float u[NB];
+#pragma unroll
+ for (int c = 0; c < NB; ++c) u[c] = 0.f;
+#pragma unroll
+ for (int i = 0; i < 4; ++i) {
+ float2 a, bb;
+ step_w(lut, s[i], a, bb);
+#pragma unroll
+ for (int c = 0; c < NB; ++c)
+ u[c] += a.x * xv[c][i].x + a.y * xv[c][i].y + bb.x * xv[c][i].z + bb.y * xv[c][i].w;
+ }
+#pragma unroll
+ for (int c = 0; c < NB; ++c) acc[r][c] += d * u[c];
+ }
+ }
+#pragma unroll
+ for (int r = 0; r < RPW; ++r)
+#pragma unroll
+ for (int c = 0; c < NB; ++c) {
+ float v = acc[r][c];
+#pragma unroll
+ for (int o = 16; o > 0; o >>= 1) v += __shfl_xor_sync(0xffffffffu, v, o);
+ if (lane == 0 && row0 + r < job.rows) job.y[(size_t) c * job.ldy + row0 + r] = v;
+ }
+}
+
+// plain dequantisation of whole rows: out[row][in] = d * codebook (F32), one thread per 4-weight step
+template <int K>
+__global__ void dequant_f32(const uint8_t* __restrict__ w, const float2* __restrict__ lut_g, float* __restrict__ out,
+ int64_t nblocks) {
+ __shared__ float2 lut[2048];
+ for (int i = threadIdx.x; i < 2048; i += blockDim.x) lut[i] = lut_g[i];
+ __syncthreads();
+ const int64_t gid = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; // unit = 4 steps
+ const int64_t b = gid >> 3;
+ if (b >= nblocks) return;
+ const int l = (int) (gid & 7);
+ const uint8_t* blk = w + b * Fmt<K>::kBlockBytes;
+ const float d = __half2float(__ushort_as_half(*(const uint16_t*) blk));
+ uint32_t s[4];
+ states4<K>((const uint16_t*) (blk + 2), l, s);
+ float4* o = (float4*) (out + b * 128 + 16 * l);
+#pragma unroll
+ for (int i = 0; i < 4; ++i) {
+ float2 a, bb;
+ step_w(lut, s[i], a, bb);
+ o[i] = make_float4(d * a.x, d * a.y, d * bb.x, d * bb.y);
+ }
+}
+
+} // namespace tqlab
diff --git a/tools/dsv41_lab/tqk_lab.cu b/tools/dsv41_lab/tqk_lab.cu
new file mode 100644
index 000000000..f227443a9
--- /dev/null
+++ b/tools/dsv41_lab/tqk_lab.cu
@@ -0,0 +1,213 @@
+// tools/dsv41_lab/tqk_lab.cu - parity + speed of the trellis expert kernels (tqk_gemv.cuh) with synthetic weights.
+// tqk_lab [--k 4,5,6,7] [--nb 1,2,3,4,5] [--reps 200] [--quick]
+// Parity: dequant vs tqenc::decode_blocks (bit exact), GEMV vs a double reference on the host-decoded weights.
+// Bench: one decode token of a routed layer = top-6 experts x (gate, up: 2304 x 5120; down: 5120 x 2304).
+#include "tqk_gemv.cuh"
+#include "../trellis/tqenc.hpp"
+
+#include <algorithm>
+#include <cmath>
+#include <cstdio>
+#include <cstdlib>
+#include <cstring>
+#include <string>
+#include <vector>
+
+#define CK(x) do { cudaError_t e_ = (x); if (e_ != cudaSuccess) { std::printf("CUDA error %s at %s:%d\n", cudaGetErrorString(e_), __FILE__, __LINE__); std::exit(2); } } while (0)
+
+using namespace tqlab;
+
+static uint64_t g_rng = 0x9e3779b97f4a7c15ull;
+static uint64_t rnd() { g_rng ^= g_rng << 13; g_rng ^= g_rng >> 7; g_rng ^= g_rng << 17; return g_rng; }
+static float frnd() { return (float) ((rnd() >> 40) * (1.0 / 16777216.0)) * 2.f - 1.f; }
+
+static int type_of(int K) { return K == 4 ? 225 : K == 5 ? 224 : K == 6 ? 145 : 146; }
+
+// random legal weights: any bit pattern is a legal stream; scale = a normal-ish fp16 in [0.02, 0.5]
+static void fill_random(std::vector<uint8_t>& w, int K, int64_t nblocks) {
+ const int bsz = 2 + 4 * K;
+ w.resize((size_t) nblocks * bsz);
+ for (size_t i = 0; i < w.size(); i += 8) { uint64_t r = rnd(); std::memcpy(&w[i], &r, std::min<size_t>(8, w.size() - i)); }
+ for (int64_t b = 0; b < nblocks; ++b) {
+ const uint16_t d = tqenc::float_to_half(0.02f + 0.48f * (frnd() * 0.5f + 0.5f));
+ std::memcpy(&w[(size_t) b * bsz], &d, 2);
+ }
+}
+
+__global__ void rd_kernel(const float4* p, size_t n4, float* o) {
+ float s = 0;
+ for (size_t i = blockIdx.x * (size_t) blockDim.x + threadIdx.x; i < n4; i += (size_t) gridDim.x * blockDim.x) { float4 v = p[i]; s += v.x + v.y + v.z + v.w; }
+ if (s == 1234.5f) *o = s;
+}
+typedef void (*gemv_fn)(const Job*, const float2*, int);
+template <int K, int NB, int RPW> static gemv_fn pick_rpw(int rpw) { (void) rpw; return gemv_v1<K, NB, RPW>; }
+template <int K, int NB> static gemv_fn pick(int variant) {
+ switch (variant) {
+ case 1: return gemv_v1<K, NB, 1>;
+ default: return gemv_v1<K, NB, 2>;
+ }
+}
+template <int K> static gemv_fn pick_nb(int nb, int variant) {
+ switch (nb) {
+ case 1: return pick<K, 1>(variant);
+ case 2: return pick<K, 2>(variant);
+ case 3: return pick<K, 3>(variant);
+ case 4: return pick<K, 4>(variant);
+ default: return pick<K, 5>(variant);
+ }
+}
+static gemv_fn pick_k(int K, int nb, int variant) {
+ switch (K) {
+ case 4: return pick_nb<4>(nb, variant);
+ case 5: return pick_nb<5>(nb, variant);
+ case 6: return pick_nb<6>(nb, variant);
+ default: return pick_nb<7>(nb, variant);
+ }
+}
+static int variant_rpw(int variant) { return variant == 1 ? 1 : 2; }
+
+static void launch(gemv_fn f, int variant, const Job* jd, int njobs, int rows, int in, const float2* lut, cudaStream_t s = 0) {
+ const int rpw = variant_rpw(variant), per_cta = 8 * rpw;
+ dim3 grid((rows + per_cta - 1) / per_cta, njobs);
+ f<<<grid, 256, 0, s>>>(jd, lut, in);
+}
+
+static float* dev_f32(const std::vector<float>& h) {
+ float* d; CK(cudaMalloc(&d, h.size() * 4)); CK(cudaMemcpy(d, h.data(), h.size() * 4, cudaMemcpyHostToDevice)); return d;
+}
+
+int main(int argc, char** argv) {
+ std::vector<int> Ks = {4, 5, 6, 7}, NBs = {1, 2, 3, 4, 5};
+ int reps = 200, variant = 2, dev = 0;
+ bool quick = false;
+ auto parse = [](const char* s) { std::vector<int> v; for (const char* p = s; *p;) { v.push_back(std::atoi(p)); while (*p && *p != ',') ++p; if (*p) ++p; } return v; };
+ for (int i = 1; i < argc; ++i) {
+ std::string a = argv[i];
+ if (a == "--k" && i + 1 < argc) Ks = parse(argv[++i]);
+ else if (a == "--nb" && i + 1 < argc) NBs = parse(argv[++i]);
+ else if (a == "--reps" && i + 1 < argc) reps = std::atoi(argv[++i]);
+ else if (a == "--variant" && i + 1 < argc) variant = std::atoi(argv[++i]);
+ else if (a == "--dev" && i + 1 < argc) dev = std::atoi(argv[++i]);
+ else if (a == "--quick") quick = true;
+ }
+ CK(cudaSetDevice(dev));
+ cudaDeviceProp prop; CK(cudaGetDeviceProperties(&prop, dev));
+ std::printf("device %s sm_%d%d, %d SMs, mem clock %d kHz bus %d bit\n", prop.name, prop.major, prop.minor, prop.multiProcessorCount,
+ prop.memoryClockRate, prop.memoryBusWidth);
+
+ // point table (x, y) as the CPU decoder sees it
+ const float* pt = tqenc::point_table();
+ float2* lut; CK(cudaMalloc(&lut, 2048 * sizeof(float2))); CK(cudaMemcpy(lut, pt, 2048 * sizeof(float2), cudaMemcpyHostToDevice));
+
+ // streaming bandwidth baseline: read-only sum over 512 MB
+ {
+ const size_t n = 128u << 20; // floats
+ float4* buf; CK(cudaMalloc(&buf, n * 4)); CK(cudaMemset(buf, 0, n * 4));
+ cudaEvent_t e0, e1; cudaEventCreate(&e0); cudaEventCreate(&e1);
+ float* o; CK(cudaMalloc(&o, 4));
+ rd_kernel<<<prop.multiProcessorCount * 8, 256>>>(buf, n / 4, o); CK(cudaDeviceSynchronize());
+ cudaEventRecord(e0);
+ for (int i = 0; i < 10; ++i) rd_kernel<<<prop.multiProcessorCount * 8, 256>>>(buf, n / 4, o);
+ cudaEventRecord(e1); CK(cudaEventSynchronize(e1));
+ float ms; cudaEventElapsedTime(&ms, e0, e1);
+ std::printf("stream-read baseline: %.1f GB/s (spec 448)\n", 10.0 * n * 4 / (ms * 1e-3) / 1e9);
+ cudaFree(buf); cudaFree(o);
+ }
+
+ int fails = 0;
+ for (int K : Ks) {
+ const int type = type_of(K), bsz = 2 + 4 * K;
+ std::printf("\n== K=%d (type %d, %d B / 128 weights, %.3f bpw) ==\n", K, type, bsz, bsz * 8 / 128.0);
+ // ---- parity 1: dequant bit exact vs the CPU decoder (random streams + encoded N(0,1) rows)
+ {
+ const int64_t nblocks = 4096;
+ std::vector<uint8_t> w; fill_random(w, K, nblocks);
+ // second half: really encoded Gaussian weights
+ const int64_t nenc = 256;
+ std::vector<float> g(nenc * 128); for (auto& v : g) { float u = 0; for (int i = 0; i < 12; ++i) u += frnd() * 0.5f + 0.5f; v = u - 6.f; }
+ std::vector<uint8_t> enc(nenc * bsz);
+ tqenc::Params p; double err = 0; int64_t nf = 0, zb = 0;
+ err = tqenc::encode_blocks(type, g.data(), nullptr, nenc, enc.data(), p, 4, nullptr, &nf, &zb);
+ std::memcpy(&w[(size_t) (nblocks - nenc) * bsz], enc.data(), enc.size());
+ std::vector<float> ref((size_t) nblocks * 128);
+ tqenc::decode_blocks(type, w.data(), nblocks, ref.data());
+ uint8_t* dw; float* dout; CK(cudaMalloc(&dw, w.size())); CK(cudaMalloc(&dout, ref.size() * 4));
+ CK(cudaMemcpy(dw, w.data(), w.size(), cudaMemcpyHostToDevice));
+ const int thr = 256; const int64_t units = nblocks * 8;
+ auto fn = K == 4 ? dequant_f32<4> : K == 5 ? dequant_f32<5> : K == 6 ? dequant_f32<6> : dequant_f32<7>;
+ fn<<<(int) ((units + thr - 1) / thr), thr>>>(dw, lut, dout, nblocks); CK(cudaGetLastError());
+ std::vector<float> got(ref.size()); CK(cudaMemcpy(got.data(), dout, got.size() * 4, cudaMemcpyDeviceToHost));
+ size_t bad = 0; for (size_t i = 0; i < got.size(); ++i) if (std::memcmp(&got[i], &ref[i], 4) != 0) ++bad;
+ double sq = 0, ee = 0; for (int64_t i = 0; i < nenc * 128; ++i) { const double r = got[(size_t) (nblocks - nenc) * 128 + i]; sq += (double) g[i] * g[i]; ee += (r - g[i]) * (r - g[i]); }
+ std::printf("dequant: %zu / %zu weights differ from tqenc::decode_blocks (bit exact %s); encoded N(0,1) SQNR %.2f dB (encoder err %.3f)\n",
+ bad, got.size(), bad ? "NO" : "yes", 10 * std::log10(sq / ee), err / (nenc * 128));
+ fails += bad != 0;
+ // ---- parity 2: GEMV vs double reference on the decoded weights, rows x in small
+ for (int nb : NBs) {
+ const int rows = 96, in = 640, nblk = in / 128;
+ std::vector<uint8_t> mw; fill_random(mw, K, (int64_t) rows * nblk);
+ std::vector<float> dec((size_t) rows * in); tqenc::decode_blocks(type, mw.data(), (int64_t) rows * nblk, dec.data());
+ std::vector<float> x((size_t) nb * in); for (auto& v : x) v = frnd();
+ std::vector<double> ref((size_t) nb * rows), refabs((size_t) nb * rows);
+ for (int c = 0; c < nb; ++c) for (int r = 0; r < rows; ++r) { double s = 0, sa = 0; for (int i = 0; i < in; ++i) { const double t = (double) dec[(size_t) r * in + i] * x[(size_t) c * in + i]; s += t; sa += std::fabs(t); } ref[(size_t) c * rows + r] = s; refabs[(size_t) c * rows + r] = sa; }
+ uint8_t* mwd; CK(cudaMalloc(&mwd, mw.size())); CK(cudaMemcpy(mwd, mw.data(), mw.size(), cudaMemcpyHostToDevice));
+ float* xd = dev_f32(x); float* yd; CK(cudaMalloc(&yd, (size_t) nb * rows * 4));
+ Job j{mwd, xd, yd, rows, in, rows}; Job* jd; CK(cudaMalloc(&jd, sizeof(Job))); CK(cudaMemcpy(jd, &j, sizeof(Job), cudaMemcpyHostToDevice));
+ launch(pick_k(K, nb, variant), variant, jd, 1, rows, in, lut); CK(cudaGetLastError());
+ std::vector<float> y((size_t) nb * rows); CK(cudaMemcpy(y.data(), yd, y.size() * 4, cudaMemcpyDeviceToHost));
+ double worst = 0; for (size_t i = 0; i < y.size(); ++i) worst = std::max(worst, std::fabs(y[i] - ref[i]) / (refabs[i] + 1e-30));
+ const bool ok = worst < 2e-6;
+ std::printf("gemv nb=%d: max |y - ref| / sum|w x| = %.2e %s\n", nb, worst, ok ? "ok" : "FAIL");
+ fails += !ok;
+ cudaFree(mwd); cudaFree(xd); cudaFree(yd); cudaFree(jd);
+ }
+ cudaFree(dw); cudaFree(dout);
+ }
+ if (quick) continue;
+ // ---- bench: top-6 experts of a layer, gate/up 2304 x 5120 (12 matrices), down 5120 x 2304 (6 matrices)
+ const int E = 6;
+ const int rows_gu = 2304, in_gu = 5120, rows_dn = 5120, in_dn = 2304;
+ const size_t mat_gu = (size_t) rows_gu * (in_gu / 128) * bsz, mat_dn = (size_t) rows_dn * (in_dn / 128) * bsz;
+ std::vector<uint8_t> hw;
+ fill_random(hw, K, (int64_t) rows_gu * (in_gu / 128));
+ uint8_t* big; CK(cudaMalloc(&big, mat_gu * 2 * E + mat_dn * E));
+ // distinct bytes per matrix (so nothing is cached across matrices): reuse one random block with different scales is
+ // not needed, the memory system does not see values; upload the same bytes to each slot.
+ std::vector<Job> hj_gu, hj_dn;
+ const int maxnb = *std::max_element(NBs.begin(), NBs.end());
+ std::vector<float> xg((size_t) maxnb * in_gu), xdn((size_t) E * maxnb * in_dn);
+ for (auto& v : xg) v = frnd(); for (auto& v : xdn) v = frnd();
+ float* xg_d = dev_f32(xg); float* xdn_d = dev_f32(xdn);
+ float* yg_d; CK(cudaMalloc(&yg_d, (size_t) 2 * E * maxnb * rows_gu * 4)); float* yd_d; CK(cudaMalloc(&yd_d, (size_t) E * maxnb * rows_dn * 4));
+ for (int e = 0; e < E; ++e) {
+ for (int m = 0; m < 2; ++m) {
+ uint8_t* p = big + (size_t) (e * 2 + m) * mat_gu;
+ CK(cudaMemcpy(p, hw.data(), mat_gu, cudaMemcpyHostToDevice));
+ hj_gu.push_back(Job{p, xg_d, yg_d + (size_t) (e * 2 + m) * maxnb * rows_gu, rows_gu, in_gu, rows_gu});
+ }
+ uint8_t* p = big + 2 * E * mat_gu + (size_t) e * mat_dn;
+ std::vector<uint8_t> hd; fill_random(hd, K, (int64_t) rows_dn * (in_dn / 128));
+ CK(cudaMemcpy(p, hd.data(), mat_dn, cudaMemcpyHostToDevice));
+ hj_dn.push_back(Job{p, xdn_d + (size_t) e * maxnb * in_dn, yd_d + (size_t) e * maxnb * rows_dn, rows_dn, in_dn, rows_dn});
+ }
+ Job *jgu, *jdn; CK(cudaMalloc(&jgu, sizeof(Job) * hj_gu.size())); CK(cudaMalloc(&jdn, sizeof(Job) * hj_dn.size()));
+ CK(cudaMemcpy(jgu, hj_gu.data(), sizeof(Job) * hj_gu.size(), cudaMemcpyHostToDevice)); CK(cudaMemcpy(jdn, hj_dn.data(), sizeof(Job) * hj_dn.size(), cudaMemcpyHostToDevice));
+ const double bytes_layer = (double) (mat_gu * 2 + mat_dn) * E, weights_layer = (double) (rows_gu * (double) in_gu * 2 + rows_dn * (double) in_dn) * E;
+ // flush L2 between reps would only matter for tiny sets: 6 x 3 matrices exceed the 4 MB L2 many times over.
+ for (int nb : NBs) {
+ gemv_fn f = pick_k(K, nb, variant);
+ cudaEvent_t e0, e1; cudaEventCreate(&e0); cudaEventCreate(&e1);
+ for (int w = 0; w < 5; ++w) { launch(f, variant, jgu, 2 * E, rows_gu, in_gu, lut); launch(f, variant, jdn, E, rows_dn, in_dn, lut); }
+ CK(cudaDeviceSynchronize()); cudaEventRecord(e0);
+ for (int r = 0; r < reps; ++r) { launch(f, variant, jgu, 2 * E, rows_gu, in_gu, lut); launch(f, variant, jdn, E, rows_dn, in_dn, lut); }
+ cudaEventRecord(e1); CK(cudaEventSynchronize(e1)); CK(cudaGetLastError());
+ float ms; cudaEventElapsedTime(&ms, e0, e1); const double us = ms * 1e3 / reps;
+ const double gbs = bytes_layer / (us * 1e-6) / 1e9, roof_us = bytes_layer / 448e9 * 1e6;
+ std::printf("bench nb=%d: %8.1f us / layer (top-6 gate+up+down) %6.1f GB/s %6.2f Gweights/s roof(448 GB/s) %7.1f us = %4.1f%% of roof | 43 layers: %.2f ms\n",
+ nb, us, gbs, weights_layer / (us * 1e-6) / 1e9, roof_us, 100 * roof_us / us, us * 43 / 1e3);
+ }
+ cudaFree(big); cudaFree(jgu); cudaFree(jdn); cudaFree(xg_d); cudaFree(xdn_d); cudaFree(yg_d); cudaFree(yd_d);
+ }
+ std::printf("\n%s (%d failures)\n", fails ? "FAILED" : "ALL PARITY OK", fails);
+ return fails ? 1 : 0;
+}
diff --git a/tools/trellis/tqenc.cpp b/tools/trellis/tqenc.cpp
new file mode 100644
index 000000000..67e1e9974
--- /dev/null
+++ b/tools/trellis/tqenc.cpp
@@ -0,0 +1,577 @@
+// tools/trellis/tqenc.cpp - see tqenc.hpp.
+#include "tqenc.hpp"
+
+#include "ggml-common-tq.h"
+
+#include <algorithm>
+#include <atomic>
+#include <cmath>
+#include <cstdlib>
+#include <cstring>
+#include <memory>
+#include <mutex>
+#include <thread>
+#include <vector>
+
+#if defined(__AVX2__) && defined(__FMA__)
+#include <immintrin.h>
+#define TQENC_AVX2 1
+#endif
+
+namespace tqenc {
+namespace {
+
+constexpr float kInf = 1e30f;
+
+// ---------------------------------------------------------------------------------------------------------------
+// fp16
+
+} // namespace
+
+float half_to_float(uint16_t h) {
+ const uint32_t sign = (uint32_t) (h & 0x8000u) << 16;
+ uint32_t exp = (h >> 10) & 0x1fu, man = h & 0x3ffu, bits;
+ if (exp == 0x1fu) {
+ bits = sign | 0x7f800000u | (man << 13);
+ } else if (exp != 0) {
+ bits = sign | ((exp + 112u) << 23) | (man << 13);
+ } else if (man == 0) {
+ bits = sign;
+ } else {
+ const float m = (float) man * (1.0f / 16777216.0f);
+ return sign ? -m : m;
+ }
+ float f;
+ std::memcpy(&f, &bits, 4);
+ return f;
+}
+
+uint16_t float_to_half(float f) {
+ uint32_t x;
+ std::memcpy(&x, &f, 4);
+ const uint32_t sign = (x >> 16) & 0x8000u;
+ const uint32_t ax = x & 0x7fffffffu;
+ if (ax >= 0x7f800000u) return (uint16_t) (sign | 0x7c00u | (ax > 0x7f800000u ? 0x200u : 0u)); // inf / nan
+ if (ax >= 0x477ff000u) return (uint16_t) (sign | 0x7c00u); // >= 65520 rounds to inf
+ if (ax < 0x33000001u) return (uint16_t) sign; // <= 2^-25: rounds to zero (ties to even)
+ int e = (int) (ax >> 23) - 127;
+ uint32_t man = (ax & 0x7fffffu) | 0x800000u;
+ if (e < -14) { // subnormal half
+ const int shift = -14 - e + 13; // total right shift of the 24-bit mantissa
+ const uint32_t half = 1u << (shift - 1), rest = man & ((1u << shift) - 1);
+ uint32_t q = man >> shift;
+ if (rest > half || (rest == half && (q & 1))) ++q;
+ return (uint16_t) (sign | q);
+ }
+ uint32_t q = ((uint32_t) (e + 15) << 10) | ((man >> 13) & 0x3ffu);
+ const uint32_t rest = man & 0x1fffu;
+ if (rest > 0x1000u || (rest == 0x1000u && (q & 1))) ++q; // a carry into the exponent is correct
+ return (uint16_t) (sign | q);
+}
+
+int type_kbits(int type) {
+ switch (type) {
+ case TQ2_T: return 8;
+ case TQK6: return 6;
+ case TQK7: return 7;
+ case TQK5X: return 5;
+ case TQK4X: return 4;
+ default: return 0;
+ }
+}
+
+namespace {
+
+// ---------------------------------------------------------------------------------------------------------------
+// codebook: the decoder's int16 table (round half away from zero of fp16 * 8192, as tq_cpu.cpp fill_table), SoA floats
+
+struct Codebook {
+ int16_t tab[kStates * 4];
+ alignas(64) float soa[4][kStates];
+ Codebook() {
+ for (uint32_t s = 0; s < (uint32_t) kStates; ++s) {
+ const uint32_t x = s * 0x9e3779b1u;
+ const uint32_t pts[2] = {x >> 21, (x >> 10) & 2047u};
+ for (int h = 0; h < 2; ++h)
+ for (int j = 0; j < 2; ++j) {
+ const float v = half_to_float(tq_lut_f16[2 * pts[h] + j]) * 8192.0f;
+ const int16_t q = (int16_t) (v < 0.0f ? v - 0.5f : v + 0.5f);
+ tab[4 * s + 2 * h + j] = q;
+ soa[2 * h + j][s] = (float) q * (1.0f / 8192.0f);
+ }
+ }
+ }
+};
+
+const Codebook& cb() {
+ static const Codebook c;
+ return c;
+}
+
+struct Geo {
+ int K = 0;
+ bool t2 = false; // TQ2_T (byte stream, the other shift direction)
+ int G = 0; // predecessor groups
+};
+
+Geo geo_for(int type) {
+ Geo g;
+ g.K = type_kbits(type);
+ g.t2 = type == TQ2_T;
+ g.G = g.t2 ? 128 : (1 << (15 - g.K));
+ return g;
+}
+
+// group of a state as a successor / as a predecessor
+inline int gsucc(const Geo& g, uint32_t s) { return g.t2 ? (int) (s >> 8) : (int) (s & (uint32_t) (g.G - 1)); }
+inline int gpred(const Geo& g, uint32_t s) { return g.t2 ? (int) (s & 0x7f) : (int) (s >> g.K); }
+
+// weight index (0..127) of component j of processing position p
+inline int widx(const Geo& g, int p, int j) { return g.t2 ? 4 * p + j : 4 * (31 - p) + j; }
+
+struct Scratch {
+ alignas(64) float D[2][kStates]; // the two live columns of the DP
+ alignas(64) uint16_t bp[32][2048]; // per step and predecessor group: the best predecessor state
+ alignas(64) float m[2048];
+ alignas(64) int32_t am[2048];
+ alignas(64) float zero[kStates];
+};
+
+Scratch& scratch() {
+ thread_local std::unique_ptr<Scratch> s;
+ if (!s) {
+ s.reset(new Scratch);
+ std::memset(s->zero, 0, sizeof s->zero);
+ std::memset(s->m, 0, sizeof s->m);
+ }
+ return *s;
+}
+
+inline float min_range(const float* p, int n) {
+#if TQENC_AVX2
+ if (n >= 8) {
+ __m256 v = _mm256_loadu_ps(p);
+ for (int i = 8; i + 8 <= n; i += 8) v = _mm256_min_ps(v, _mm256_loadu_ps(p + i));
+ __m128 a = _mm_min_ps(_mm256_castps256_ps128(v), _mm256_extractf128_ps(v, 1));
+ a = _mm_min_ps(a, _mm_movehl_ps(a, a));
+ a = _mm_min_ss(a, _mm_shuffle_ps(a, a, 1));
+ return _mm_cvtss_f32(a);
+ }
+#endif
+ float m = p[0];
+ for (int i = 1; i < n; ++i) m = std::min(m, p[i]);
+ return m;
+}
+
+// out[i] = add[i] + sum_j h_j (t_j - cb_j[s0 + i])^2 for i in [0, n)
+inline void step_cost(float* out, const float* add, int s0, int n, const float* t, const float* h) {
+ const float *c0 = cb().soa[0] + s0, *c1 = cb().soa[1] + s0, *c2 = cb().soa[2] + s0, *c3 = cb().soa[3] + s0;
+ int i = 0;
+#if TQENC_AVX2
+ const __m256 t0 = _mm256_set1_ps(t[0]), t1 = _mm256_set1_ps(t[1]), t2 = _mm256_set1_ps(t[2]), t3 = _mm256_set1_ps(t[3]);
+ const __m256 h0 = _mm256_set1_ps(h[0]), h1 = _mm256_set1_ps(h[1]), h2 = _mm256_set1_ps(h[2]), h3 = _mm256_set1_ps(h[3]);
+ for (; i + 8 <= n; i += 8) {
+ const __m256 e0 = _mm256_sub_ps(t0, _mm256_loadu_ps(c0 + i)), e1 = _mm256_sub_ps(t1, _mm256_loadu_ps(c1 + i));
+ const __m256 e2 = _mm256_sub_ps(t2, _mm256_loadu_ps(c2 + i)), e3 = _mm256_sub_ps(t3, _mm256_loadu_ps(c3 + i));
+ __m256 a = _mm256_fmadd_ps(_mm256_mul_ps(h0, e0), e0, _mm256_loadu_ps(add + i));
+ a = _mm256_fmadd_ps(_mm256_mul_ps(h1, e1), e1, a);
+ a = _mm256_fmadd_ps(_mm256_mul_ps(h2, e2), e2, a);
+ a = _mm256_fmadd_ps(_mm256_mul_ps(h3, e3), e3, a);
+ _mm256_storeu_ps(out + i, a);
+ }
+#endif
+ for (; i < n; ++i) {
+ const float e0 = t[0] - c0[i], e1 = t[1] - c1[i], e2 = t[2] - c2[i], e3 = t[3] - c3[i];
+ out[i] = add[i] + h[0] * e0 * e0 + h[1] * e1 * e1 + h[2] * e2 * e2 + h[3] * e3 * e3;
+ }
+}
+
+// the broadcast variant: out[i] = a + cost(s0 + i)
+inline void step_cost_bc(float* out, float a, int s0, int n, const float* t, const float* h) {
+ alignas(32) float tmp[256];
+ for (int i = 0; i < n; ++i) tmp[i] = a;
+ step_cost(out, tmp, s0, n, t, h);
+}
+
+// min and first index of the minimum over p[0..n)
+inline float min_arg_range(const float* p, int n, int* arg) {
+ const float m = min_range(p, n);
+ int i = 0;
+#if TQENC_AVX2
+ const __m256 vm = _mm256_set1_ps(m);
+ for (; i + 8 <= n; i += 8) {
+ const int mask = _mm256_movemask_ps(_mm256_cmp_ps(_mm256_loadu_ps(p + i), vm, _CMP_EQ_OQ));
+ if (mask) { *arg = i + __builtin_ctz((unsigned) mask); return m; }
+ }
+#endif
+ for (; i < n; ++i)
+ if (p[i] == m) { *arg = i; return m; }
+ *arg = 0;
+ return m;
+}
+
+// T[p][4]: targets of processing position p (weights / d), H[p][4]: importance. rot: the sequence is processed from
+// position rot (cyclically); fixed_c >= 0: tail-biting with the successor group of the first state and the predecessor
+// group of the last state both == fixed_c. Writes the states by position into st[32]; returns the path cost.
+float viterbi(const Geo& g, const float (*T)[4], const float (*H)[4], int rot, int fixed_c, uint16_t* st) {
+ Scratch& sc = scratch();
+ const int K = g.K, G = g.G;
+ float* cur = sc.D[0];
+ // q = 0
+ {
+ const int p = rot & 31;
+ step_cost(cur, sc.zero, 0, kStates, T[p], H[p]);
+ if (fixed_c >= 0) {
+ if (g.t2) { // gsucc(s) = s >> 8 == c: the 256 states [c<<8, c<<8 + 256) allowed
+ for (int s = 0; s < kStates; ++s)
+ if ((s >> 8) != fixed_c) cur[s] = kInf;
+ } else { // s & (G-1) == c
+ for (int s = 0; s < kStates; ++s)
+ if ((s & (G - 1)) != fixed_c) cur[s] = kInf;
+ }
+ }
+ }
+ for (int q = 1; q < 32; ++q) {
+ const float* prev = cur;
+ cur = sc.D[q & 1];
+ const int p = (rot + q) & 31;
+ float* m = sc.m;
+ uint16_t* bp = sc.bp[q];
+ if (g.t2) {
+ // m[a] = min over h of prev[a + 128 h], argmin h
+ for (int a = 0; a < 128; ++a) { m[a] = prev[a]; sc.am[a] = 0; }
+ for (int h = 1; h < 256; ++h) {
+ const float* row = prev + 128 * h;
+ int a = 0;
+#if TQENC_AVX2
+ const __m256i vh = _mm256_set1_epi32(h);
+ for (; a + 8 <= 128; a += 8) {
+ const __m256 r = _mm256_loadu_ps(row + a), mm = _mm256_loadu_ps(m + a);
+ const __m256 lt = _mm256_cmp_ps(r, mm, _CMP_LT_OQ); // strictly smaller: the first minimum stays
+ _mm256_storeu_ps(m + a, _mm256_blendv_ps(mm, r, lt));
+ const __m256i old = _mm256_loadu_si256((const __m256i*) (sc.am + a));
+ _mm256_storeu_si256((__m256i*) (sc.am + a), _mm256_castps_si256(_mm256_blendv_ps(
+ _mm256_castsi256_ps(old), _mm256_castsi256_ps(vh), lt)));
+ }
+#endif
+ for (; a < 128; ++a)
+ if (row[a] < m[a]) { m[a] = row[a]; sc.am[a] = h; }
+ }
+ for (int a = 0; a < 128; ++a) bp[a] = (uint16_t) (a + 128 * sc.am[a]);
+ for (int b = 0; b < 128; ++b) step_cost_bc(cur + 256 * b, m[b], 256 * b, 256, T[p], H[p]);
+ } else {
+ const int span = 1 << K;
+ for (int a = 0; a < G; ++a) {
+ int arg;
+ m[a] = min_arg_range(prev + (size_t) a * span, span, &arg);
+ bp[a] = (uint16_t) ((a << K) + arg);
+ }
+ for (int base = 0; base < kStates; base += G) step_cost(cur + base, m, base, G, T[p], H[p]);
+ }
+ }
+ // final state
+ const float* last = cur;
+ int best = -1;
+ float bc = 3e38f;
+ if (fixed_c < 0) {
+ for (int s = 0; s < kStates; ++s)
+ if (last[s] < bc) { bc = last[s]; best = s; }
+ } else if (g.t2) {
+ for (int h = 0; h < 256; ++h) {
+ const int s = fixed_c + 128 * h;
+ if (last[s] < bc) { bc = last[s]; best = s; }
+ }
+ } else {
+ for (int i = 0; i < (1 << K); ++i) {
+ const int s = (fixed_c << K) + i;
+ if (last[s] < bc) { bc = last[s]; best = s; }
+ }
+ }
+ if (best < 0 || bc >= kInf * 0.5f) return kInf;
+ uint32_t s = (uint32_t) best;
+ st[(rot + 31) & 31] = (uint16_t) s;
+ for (int q = 31; q >= 1; --q) {
+ s = sc.bp[q][gsucc(g, s)];
+ st[(rot + q - 1) & 31] = (uint16_t) s;
+ }
+ return bc;
+}
+
+// junction group of a free pass: gpred of the state at orig position 31 (== gsucc of the state at position 0)
+inline int junction_group(const Geo& g, const uint16_t* st) { return gpred(g, st[31]); }
+
+struct Search {
+ const Geo* g;
+ const Params* p;
+ float T[32][4];
+ float H[32][4];
+ uint16_t st[32];
+ int passes = 0;
+
+ // one tail-biting search at scale d (weights already divided: set_targets); returns the path cost in scaled units
+ float run() {
+ static const int rots[8] = {16, 8, 24, 12, 20, 4, 28, 0};
+ float best = kInf;
+ uint16_t tmp[32], free_st[32];
+ if (p->exact) {
+ for (int c = 0; c < g->G; ++c) {
+ const float v = viterbi(*g, T, H, 0, c, tmp);
+ ++passes;
+ if (v < best) { best = v; std::memcpy(st, tmp, sizeof tmp); }
+ }
+ return best;
+ }
+ int seen[8], ns = 0;
+ const int nc = std::max(1, std::min(p->ncand, 8));
+ for (int r = 0; r < nc; ++r) {
+ viterbi(*g, T, H, rots[r], -1, free_st);
+ ++passes;
+ const int c = junction_group(*g, free_st);
+ bool dup = false;
+ for (int i = 0; i < ns; ++i) dup |= seen[i] == c;
+ if (dup) continue;
+ seen[ns++] = c;
+ const float v = viterbi(*g, T, H, 0, c, tmp);
+ ++passes;
+ if (v < best) { best = v; std::memcpy(st, tmp, sizeof tmp); }
+ }
+ return best;
+ }
+};
+
+void pack_stream(const Geo& g, const uint16_t* st, uint8_t* qs) {
+ const int K = g.K;
+ std::memset(qs, 0, (size_t) 4 * K);
+ if (g.t2) {
+ for (int t = 0; t < 32; ++t) qs[t] = (uint8_t) (st[t] & 0xff);
+ return;
+ }
+ for (int u = 0; u < 32; ++u) {
+ const uint32_t x = st[u] & ((1u << K) - 1u);
+ for (int b = 0; b < K; ++b)
+ if ((x >> b) & 1u) qs[(u * K + b) >> 3] |= (uint8_t) (1u << ((u * K + b) & 7));
+ }
+}
+
+} // namespace
+
+float debug_viterbi(int type, const float (*T)[4], const float (*H)[4], int rot, int fixed_c, uint16_t* st) {
+ return viterbi(geo_for(type), T, H, rot, fixed_c, st);
+}
+int debug_groups(int type) { return geo_for(type).G; }
+int debug_widx(int type, int p, int j) { return widx(geo_for(type), p, j); }
+void debug_pack(int type, const uint16_t* st, uint8_t* qs) { pack_stream(geo_for(type), st, qs); }
+
+const float* codebook_state(uint32_t state) {
+ static thread_local float v[4];
+ for (int j = 0; j < 4; ++j) v[j] = cb().soa[j][state & 0x7fff];
+ return v;
+}
+
+const int16_t* codebook_table() { return cb().tab; }
+
+const float* point_table() {
+ static float pts[4096];
+ static std::once_flag once;
+ std::call_once(once, [] {
+ for (int i = 0; i < 4096; ++i) {
+ const float x = half_to_float(tq_lut_f16[i]) * 8192.0f;
+ const int16_t q = (int16_t) (x < 0.0f ? x - 0.5f : x + 0.5f);
+ pts[i] = (float) q * (1.0f / 8192.0f);
+ }
+ });
+ return pts;
+}
+
+uint32_t block_state(int type, const uint8_t* qs, int t) {
+ const int K = type_kbits(type);
+ if (type == TQ2_T) return (((uint32_t) qs[(t + 31) & 31] << 8) | qs[t]) & 0x7fffu;
+ const int total = 32 * K;
+ uint32_t s = 0;
+ for (int i = 0; i < 15; ++i) {
+ const int b = ((31 - t) * K + i) % total;
+ s |= (uint32_t) ((qs[b >> 3] >> (b & 7)) & 1u) << i;
+ }
+ return s;
+}
+
+void decode_blocks(int type, const uint8_t* src, int64_t nblocks, float* out) {
+ const int K = type_kbits(type), bb = 2 + 4 * K;
+ for (int64_t b = 0; b < nblocks; ++b) {
+ const uint8_t* blk = src + (size_t) b * bb;
+ const uint16_t dh = (uint16_t) (blk[0] | (blk[1] << 8));
+ const float d = half_to_float(dh);
+ for (int t = 0; t < 32; ++t) {
+ const uint32_t s = block_state(type, blk + 2, t);
+ for (int j = 0; j < 4; ++j) out[b * 128 + 4 * t + j] = d * cb().soa[j][s];
+ }
+ }
+}
+
+BlockResult encode_block(int type, const float* w, const float* h, uint8_t* dst, const Params& prm) {
+ BlockResult r;
+ const Geo g = geo_for(type);
+ const int K = g.K, bb = 2 + 4 * K;
+ std::memset(dst, 0, (size_t) bb);
+ double sumw2 = 0, sumhw2 = 0, amax = 0;
+ for (int i = 0; i < 128; ++i) {
+ if (!std::isfinite(w[i]) || (h && !std::isfinite(h[i]))) { r.status = 2; r.err = NAN; return r; }
+ const double hi = h ? h[i] : 1.0;
+ sumw2 += (double) w[i] * w[i];
+ sumhw2 += hi * (double) w[i] * w[i];
+ amax = std::max(amax, (double) std::fabs(w[i]));
+ }
+ if (amax == 0.0) { r.status = 1; return r; }
+ const double rms = std::sqrt(sumw2 / 128.0);
+ // initial scale: the codebook has unit-ish rms
+ constexpr double kCbRms = 1.072;
+ static const double mult[7] = {1.0, 0.9, 1.1, 0.8, 1.2, 0.7, 1.3};
+
+ Search se;
+ se.g = &g;
+ se.p = &prm;
+ for (int p = 0; p < 32; ++p)
+ for (int j = 0; j < 4; ++j) se.H[p][j] = h ? h[widx(g, p, j)] : 1.0f;
+
+ double best_err = 1e300;
+ uint16_t best_st[32] = {};
+ uint16_t best_d = 0;
+ bool have = false;
+
+ auto fit = [&](const uint16_t* st, uint16_t dh, double& err) {
+ // err of (st, dh): sum h (w - d cv)^2
+ const float d = half_to_float(dh);
+ double e = 0;
+ for (int p = 0; p < 32; ++p)
+ for (int j = 0; j < 4; ++j) {
+ const int wi = widx(g, p, j);
+ const float rec = d * cb().soa[j][st[p]];
+ const double df = (double) w[wi] - rec;
+ e += (h ? h[wi] : 1.0) * df * df;
+ }
+ err = e;
+ };
+
+ const int tries = prm.fixed_scale ? 1 : std::max(1, std::min(prm.scale_tries, 7));
+ for (int tr = 0; tr < tries; ++tr) {
+ double dd = rms / kCbRms * mult[tr];
+ uint16_t dh = float_to_half((float) std::min(dd, 65504.0));
+ if (dh == 0) dh = 1; // the smallest subnormal: weights below ~3e-8 are noise at this scale
+ if (prm.fixed_scale) dh = prm.fixed_scale;
+ for (int it = 0; it <= (prm.fixed_scale ? 0 : prm.iters); ++it) {
+ const float d = half_to_float(dh);
+ for (int p = 0; p < 32; ++p)
+ for (int j = 0; j < 4; ++j) se.T[p][j] = w[widx(g, p, j)] / d;
+ if (se.run() >= kInf * 0.5f) break;
+ double e;
+ fit(se.st, dh, e);
+ if (e < best_err) {
+ best_err = e;
+ best_d = dh;
+ std::memcpy(best_st, se.st, sizeof best_st);
+ have = true;
+ }
+ if (e == 0.0 || prm.fixed_scale) break;
+ // least-squares scale for this path
+ double num = 0, den = 0;
+ for (int p = 0; p < 32; ++p)
+ for (int j = 0; j < 4; ++j) {
+ const int wi = widx(g, p, j);
+ const double hi = h ? h[wi] : 1.0, c = cb().soa[j][se.st[p]];
+ num += hi * w[wi] * c;
+ den += hi * c * c;
+ }
+ if (den <= 0 || num <= 0) break;
+ uint16_t nh = float_to_half((float) std::min(num / den, 65504.0));
+ if (nh == 0 || nh == dh) break;
+ double en;
+ fit(se.st, nh, en);
+ if (en < best_err) {
+ best_err = en;
+ best_d = nh;
+ std::memcpy(best_st, se.st, sizeof best_st);
+ }
+ if (en >= e) break; // the scale step did not help this path: stop refining this start
+ dh = nh;
+ }
+ r.searches = se.passes;
+ }
+ if (!have || best_err >= sumhw2) { // nothing beats a zero block (weights below the fp16 scale resolution)
+ std::memset(dst, 0, (size_t) bb);
+ r.status = 1;
+ r.err = sumhw2;
+ return r;
+ }
+ dst[0] = (uint8_t) (best_d & 0xff);
+ dst[1] = (uint8_t) (best_d >> 8);
+ pack_stream(g, best_st, dst + 2);
+ r.err = best_err;
+ r.scale = half_to_float(best_d);
+ r.searches = se.passes;
+ return r;
+}
+
+double encode_blocks(int type, const float* w, const float* h, int64_t nblocks, uint8_t* dst, const Params& p,
+ int nthreads, double* err_out, int64_t* nonfinite, int64_t* zero_blocks) {
+ const int bb = block_bytes(type);
+ if (nthreads <= 0) nthreads = (int) std::max(1u, std::thread::hardware_concurrency());
+ nthreads = (int) std::min<int64_t>(nthreads, std::max<int64_t>(1, nblocks));
+ std::atomic<int64_t> next{0}, nf{0}, zb{0};
+ std::vector<double> sums((size_t) nthreads, 0.0);
+ auto work = [&](int ti) {
+ double s = 0;
+ for (;;) {
+ const int64_t b0 = next.fetch_add(4);
+ if (b0 >= nblocks) break;
+ const int64_t b1 = std::min(nblocks, b0 + 4);
+ for (int64_t b = b0; b < b1; ++b) {
+ const BlockResult r = encode_block(type, w + b * 128, h ? h + b * 128 : nullptr, dst + (size_t) b * bb, p);
+ if (r.status == 2) { nf.fetch_add(1); }
+ else s += r.err;
+ if (r.status == 1) zb.fetch_add(1);
+ if (err_out) err_out[b] = r.err;
+ }
+ }
+ sums[ti] = s;
+ };
+ std::vector<std::thread> th;
+ for (int i = 1; i < nthreads; ++i) th.emplace_back(work, i);
+ work(0);
+ for (auto& t : th) t.join();
+ if (nonfinite) *nonfinite = nf.load();
+ if (zero_blocks) *zero_blocks = zb.load();
+ double tot = 0;
+ for (double s : sums) tot += s;
+ return tot;
+}
+
+} // namespace tqenc
+
+// ---------------------------------------------------------------------------------------------------------------
+// C API for the Python wrapper (tools/tqenc.py, ctypes)
+extern "C" {
+#if defined(_WIN32)
+#define TQE_EXPORT __declspec(dllexport)
+#else
+#define TQE_EXPORT __attribute__((visibility("default")))
+#endif
+TQE_EXPORT int tqe_block_bytes(int type) { return tqenc::block_bytes(type); }
+TQE_EXPORT int tqe_kbits(int type) { return tqenc::type_kbits(type); }
+TQE_EXPORT void tqe_decode(int type, const uint8_t* src, int64_t nblocks, float* out) {
+ tqenc::decode_blocks(type, src, nblocks, out);
+}
+// returns the summed block error; stats[0] = nonfinite blocks, stats[1] = zero blocks
+TQE_EXPORT double tqe_encode(int type, const float* w, const float* h, int64_t nblocks, uint8_t* dst, int iters,
+ int ncand, int exact, int scale_tries, int nthreads, double* err_out, int64_t* stats) {
+ tqenc::Params p;
+ p.iters = iters;
+ p.ncand = ncand;
+ p.exact = exact;
+ p.scale_tries = scale_tries;
+ int64_t nf = 0, zb = 0;
+ const double e = tqenc::encode_blocks(type, w, h, nblocks, dst, p, nthreads, err_out, &nf, &zb);
+ if (stats) { stats[0] = nf; stats[1] = zb; }
+ return e;
+}
+TQE_EXPORT const int16_t* tqe_table() { return tqenc::codebook_table(); }
+}
diff --git a/tools/trellis/tqenc.hpp b/tools/trellis/tqenc.hpp
new file mode 100644
index 000000000..241fb6cde
--- /dev/null
+++ b/tools/trellis/tqenc.hpp
@@ -0,0 +1,96 @@
+// tools/trellis/tqenc.hpp - tail-biting Viterbi ENCODER for the trellis expert formats (TQ2_T, TQK6, TQK7 of the
+// agentionai llama.cpp fork, ggml types 144-146) and two experimental lower-rate versions (TQK5X, TQK4X).
+//
+// Standalone (no ggml, no Strata engine): it only needs third_party/ggml/ggml-common-tq.h (the 2048-point codebook).
+// The decoders it must match are src/kernels/cpu/tq_states.hpp / tq_cpu.cpp (tools/trellis/tqenc_test.cpp checks
+// bit for bit against them, and the scalar / AVX2 / AVX-512 kernels against the encoder's own reconstruction).
+//
+// THE FORMAT (see tq_states.hpp, include/strata/kernels/cpu/tq_cpu.hpp, docs/GYRO.md):
+// block = 128 weights = {fp16 d (little endian); qs[4*K]}, 32 steps t of 4 weights (weights 4t..4t+3).
+// State of step t: 15 bits. weights = d * codebook(state); the state's hash x = state * 0x9e3779b1 picks two
+// points lut[x >> 21] and lut[(x >> 10) & 2047] (fp16 pairs) = four values. The decoder works on the int16 table
+// round(fp16 * 8192) (tq_state_table), so that table, divided by 8192, is the codebook here.
+// TQK (K = 4,5,6,7): state(t) = bits [(31-t)K, (31-t)K + 15) of the qs bit stream (LSB first), circular modulo
+// 32K bits. With u = 31 - t the states form a shift trellis: state(u+1) = (state(u) >> K) | (new K bits <<
+// (15-K)); the K low bits of state(u) are stream symbol u. Tail-biting: state(0) closes the cycle.
+// TQ2_T (K = 8): state(t) = ((qs[(t+31)%32] << 8) | qs[t]) & 0x7fff: a shift trellis in the other direction
+// (state(t) = ((state(t-1) & 0x7f) << 8) | qs[t]).
+// Both are a "de Bruijn" trellis of 2^15 states with 2^K branches per state, so one Viterbi step is a min over G
+// groups of predecessors followed by a broadcast add (G = 2^(15-K) groups for TQK, 128 for TQ2_T), not 2^15 * 2^K
+// additions. Tail-biting = a cycle of 32 states: the group of state(0) as successor equals the group of state(31)
+// as predecessor. The search fixes that group c (exact: all G values; approximate: c taken from a free Viterbi pass
+// on the cyclically rotated sequence, QTIP's approach, optionally the best of several rotations).
+//
+// New experimental types: TQK5X (id 224, 22 bytes / 128 weights, 1.375 bpw) and TQK4X (id 225, 18 bytes, 1.125 bpw):
+// the TQK rule with K = 5 / 4, nothing else changed (same hash, codebook, mask, bit order, circular stream, fp16
+// scale). EXPERIMENTAL_VERSION = 1: not in any ggml enum, not in any GGUF reader.
+#pragma once
+
+#include <cstddef>
+#include <cstdint>
+
+namespace tqenc {
+
+inline constexpr int kBlock = 128;
+inline constexpr int kStates = 1 << 15;
+inline constexpr int kExperimentalVersion = 1;
+
+// ggml type ids of the fork (decoders exist) and the experimental ones (encoder + Strata CPU decoder only)
+enum Type : int { TQ2_T = 144, TQK6 = 145, TQK7 = 146, TQK5X = 224, TQK4X = 225 };
+
+/// bits per step (8, 6, 7, 5, 4), 0 for any other type.
+int type_kbits(int type);
+inline int block_bytes(int type) { return type_kbits(type) ? 2 + 4 * type_kbits(type) : 0; }
+
+struct Params {
+ int iters = 3; ///< scale refinement rounds after the first search (path given d -> d given path)
+ int ncand = 1; ///< tail-biting start-group candidates (rotations 16, 8, 24, 12, 20, 4, 28 ...); 1 = QTIP's
+ int exact = 0; ///< 1: try every start group (the exact tail-biting optimum at the current scale; slow)
+ int scale_tries = 1; ///< initial scales d0 * {1, 0.9, 1.1, 0.8, 1.2, ...}: the best of the first n searches
+ uint16_t fixed_scale = 0; ///< nonzero: this fp16 scale is used as is (no refinement); tests, planted solutions
+};
+
+struct BlockResult {
+ double err = 0; ///< sum_i h_i (w_i - rec_i)^2 for the stored block (h = 1 without importance weights)
+ float scale = 0; ///< the stored fp16 scale
+ int searches = 0; ///< Viterbi passes run
+ int status = 0; ///< 0 ok, 1 zero block (all weights zero or below fp16 resolution), 2 nonfinite input
+};
+
+/// The codebook entry of a state as the decoder sees it: four floats (int16 table / 8192, exact).
+const float* codebook_state(uint32_t state); // 4 floats
+const int16_t* codebook_table(); // 32768 * 4 int16, the decoder's tq_state_table()
+/// The 2048 codebook points as the decoder sees them (x, y interleaved): round(fp16 * 8192) / 8192. The GPU encoder
+/// uploads this table; it must be built by the host compiler (ggml-common-tq.h makes its table __device__ under hipcc).
+const float* point_table(); // 4096 floats
+
+/// The state of step t (0..31) of a block's stream, by the decoder's rule, written bit by bit (independent of
+/// tq_states.hpp). qs = the 4K stream bytes.
+uint32_t block_state(int type, const uint8_t* qs, int t);
+
+/// Decodes `nblocks` blocks (block_bytes(type) each) to 128 floats each: d * codebook, d the fp16 scale.
+void decode_blocks(int type, const uint8_t* src, int64_t nblocks, float* out);
+
+/// Encodes one block of 128 weights (importance weights h[128] or null) into block_bytes(type) bytes.
+BlockResult encode_block(int type, const float* w, const float* h, uint8_t* dst, const Params& p);
+
+/// Encodes nblocks consecutive blocks on `nthreads` threads (0: hardware concurrency). err_out (nblocks doubles) and
+/// the returned sum of block errors are the objective sum h (w - rec)^2. Sets *nonfinite to the number of blocks
+/// with a NaN/Inf input weight (those are written as zero blocks).
+double encode_blocks(int type, const float* w, const float* h, int64_t nblocks, uint8_t* dst, const Params& p,
+ int nthreads, double* err_out, int64_t* nonfinite, int64_t* zero_blocks);
+
+/// TEST HOOK: one Viterbi pass over a scaled target (T[p][4] = weights / d of processing position p, H[p][4]) and the
+/// legal-path states by position. rot = first position processed, fixed_c = tail-biting group (-1 free).
+float debug_viterbi(int type, const float (*T)[4], const float (*H)[4], int rot, int fixed_c, uint16_t* st);
+/// Group sizes: predecessor groups G of a type; processing position p -> weight index of component j.
+int debug_groups(int type);
+int debug_widx(int type, int p, int j);
+/// the stream bytes (4K) of a state path by position, as the encoder packs them
+void debug_pack(int type, const uint16_t* st, uint8_t* qs);
+
+// fp16 helpers (round to nearest even, like the hardware; exposed for the tests)
+uint16_t float_to_half(float f);
+float half_to_float(uint16_t h);
+
+} // namespace tqenc