Merge f-dsv41-cudalab (trellis GEMV lab, tqenc) into f-dsv41-port

This commit is contained in:
Niko1221 committed 2026-10-20 18:54:44 +02:00
commit d9220bd1a5
27 files changed
+3314 -5

No files matched your search

+8 -3
View File
@@ -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).
+2
View File
@@ -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);
}
+2
View File
@@ -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);
}
+6 -2
View File
@@ -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);
}
+202
View File
@@ -0,0 +1,202 @@
// tools/dsv41_lab/attn_split.cuh - split-KV ("flash-decoding") version of DeepSeek's sparse attention for a few queries
// (decode T = 1, DSpark verify T = 2..5): 64 heads x d 512, MQA (K = V), window rows (BF16) + selected compressed rows (kKvFp4:
// E2M1 codes + E4M3 scales per 16) + a learned sink logit per head. Same inputs and outputs as strata::ds4::sparse_attn
// (AttnRows gen 0, ckv kKvFp4); the shipped kernel runs one 256-thread block per (head, query) = 64 blocks on 48 SMs and takes
// ~125 us per query; this one splits the keys over R-row chunks and groups G heads per block, which share the decoded rows.
// phase 1: block (head group, chunk, query): decode R rows to BF16 in shared memory (exact: window rows are BF16, packed
// rows have <= 7 significant bits), scores for G heads (warp per row, lanes 16 values, shuffle reduction), local
// softmax, partial output (thread = 2 output values) -> scratch {m, l, o[512]} per (query, head, chunk)
// phase 2: block (head, query): merge the chunks and the sink.
// Plain C++ (no PTX), shuffles and shared memory only: the HIP port is a rename.
#pragma once
#include "../../src/dsv41/ds4_kernels.cuh"
#include "../../src/dsv41/ds4_numerics.cuh"
#include <cuda_fp16.h>
namespace strata::ds4lab {
using strata::ds4::AttnRows;
__device__ __forceinline__ float bf2f_(uint16_t b) { return __uint_as_float((uint32_t) b << 16); }
__device__ __forceinline__ uint16_t f2bf_exact(float f) { return (uint16_t) (__float_as_uint(f) >> 16); } // exact values only
__device__ __forceinline__ float e2m1_x2p14(uint32_t c) {
return __half2float(__ushort_as_half((unsigned short) (((c & 8u) << 12) | ((c & 7u) << 9))));
}
__device__ __forceinline__ float wsum(float v) {
#pragma unroll
for (int o = 16; o > 0; o >>= 1) v += __shfl_xor_sync(0xffffffffu, v, o);
return v;
}
__device__ __forceinline__ float wmax(float v) {
#pragma unroll
for (int o = 16; o > 0; o >>= 1) v = fmaxf(v, __shfl_xor_sync(0xffffffffu, v, o));
return v;
}
// d = 512 only (a thread owns 2 output values, a lane 16 values of a row)
template <int G, int R>
__global__ void __launch_bounds__(256) attn_part(const float* __restrict__ q, const uint16_t* __restrict__ win,
const uint8_t* __restrict__ ckv, size_t ckv_row_bytes, const int* __restrict__ sel,
int sel_stride, AttnRows ar, int heads, float scale, float* __restrict__ part,
float* __restrict__ ml, int nsplit) {
constexpr int D = 512;
__shared__ __align__(16) uint16_t rows[R][D];
__shared__ float sc[G][R];
__shared__ float4 pr[R][(G + 3) / 4];
__shared__ float mloc[G], lloc[G];
const int hg = blockIdx.x, chunk = blockIdx.y, t = blockIdx.z;
const int n_win = ar.nwin[t], n_sel = ar.nsel[t], total = n_win + n_sel;
const int j0 = chunk * R;
if (j0 >= total) return;
const int nr = min(R, total - j0);
const int lane = threadIdx.x & 31, wp = threadIdx.x >> 5;
// q of this block's heads: lane's 16 values per head in registers (issued first: its latency overlaps the row loads)
float qv[G][16];
#pragma unroll
for (int g = 0; g < G; ++g) {
const float4* qp = (const float4*) (q + ((size_t) t * heads + hg * G + g) * D + lane * 16);
#pragma unroll
for (int i = 0; i < 4; ++i) { const float4 v = qp[i]; qv[g][4 * i] = v.x; qv[g][4 * i + 1] = v.y; qv[g][4 * i + 2] = v.z; qv[g][4 * i + 3] = v.w; }
}
// ---- stage rows: warp per row, lane = 16 values; all of a warp's row loads are issued before any is converted
constexpr int RPW = (R + 7) / 8;
uint4 wa[RPW][2];
uint2 cwv[RPW];
uint32_t sbv[RPW];
int rowoff[RPW];
#pragma unroll
for (int i = 0; i < RPW; ++i) {
const int jj = wp + 8 * i, j = j0 + jj;
rowoff[i] = -1;
if (jj < nr) {
if (j < n_win) {
const uint4* src = (const uint4*) (win + (size_t) (ar.win0[t] + j) * D + lane * 16);
wa[i][0] = src[0];
wa[i][1] = src[1];
} else {
rowoff[i] = sel[(size_t) t * sel_stride + (j - n_win)];
}
}
}
#pragma unroll
for (int i = 0; i < RPW; ++i)
if (rowoff[i] >= 0) {
const uint8_t* r = ckv + (size_t) rowoff[i] * ckv_row_bytes;
cwv[i] = *(const uint2*) (r + lane * 8);
sbv[i] = r[D / 2 + lane];
}
#pragma unroll
for (int i = 0; i < RPW; ++i) {
const int jj = wp + 8 * i;
if (jj >= nr) continue;
uint4* dst = (uint4*) &rows[jj][lane * 16];
if (rowoff[i] < 0) {
dst[0] = wa[i][0];
dst[1] = wa[i][1];
} else {
const float s = strata::ds4::e4m3_value((uint8_t) sbv[i]) * 16384.0f; // (the nibbles decode to value * 2^-14)
uint32_t o[8];
#pragma unroll
for (int w = 0; w < 2; ++w) {
const uint32_t c = w ? cwv[i].y : cwv[i].x;
#pragma unroll
for (int x = 0; x < 4; ++x) {
const uint32_t b = c >> (8 * x);
const uint16_t lo = f2bf_exact(e2m1_x2p14(b) * s), hi = f2bf_exact(e2m1_x2p14(b >> 4) * s);
o[4 * w + x] = (uint32_t) lo | ((uint32_t) hi << 16);
}
}
dst[0] = make_uint4(o[0], o[1], o[2], o[3]);
dst[1] = make_uint4(o[4], o[5], o[6], o[7]);
}
}
__syncthreads();
// ---- scores
for (int jj = wp; jj < nr; jj += 8) {
const uint4 a = *(const uint4*) &rows[jj][lane * 16], b = *(const uint4*) &rows[jj][lane * 16 + 8];
float kv[16];
const uint32_t w[8] = {a.x, a.y, a.z, a.w, b.x, b.y, b.z, b.w};
#pragma unroll
for (int i = 0; i < 8; ++i) { kv[2 * i] = __uint_as_float(w[i] << 16); kv[2 * i + 1] = __uint_as_float(w[i] & 0xffff0000u); }
#pragma unroll
for (int g = 0; g < G; ++g) {
float s = 0.f;
#pragma unroll
for (int i = 0; i < 16; ++i) s += qv[g][i] * kv[i];
s = wsum(s);
if (lane == 0) sc[g][jj] = s * scale;
}
}
__syncthreads();
// ---- local softmax: warp g handles head g
if (wp < G) {
float m = -INFINITY;
for (int j = lane; j < nr; j += 32) m = fmaxf(m, sc[wp][j]);
m = wmax(m);
float l = 0.f;
for (int j = lane; j < nr; j += 32) { const float p = __expf(sc[wp][j] - m); sc[wp][j] = p; l += p; }
l = wsum(l);
if (lane == 0) { mloc[wp] = m; lloc[wp] = l; }
}
__syncthreads();
for (int i = threadIdx.x; i < nr * G; i += 256) { const int j = i / G, g = i % G; ((float*) &pr[j][0])[g] = sc[g][j]; }
__syncthreads();
// ---- partial output: thread = values 2 tid, 2 tid + 1 of every head
float o0[G], o1[G];
#pragma unroll
for (int g = 0; g < G; ++g) o0[g] = o1[g] = 0.f;
const int c = threadIdx.x * 2;
for (int j = 0; j < nr; ++j) {
const uint32_t kw = *(const uint32_t*) &rows[j][c];
const float k0 = __uint_as_float(kw << 16), k1 = __uint_as_float(kw & 0xffff0000u);
const float* p = (const float*) &pr[j][0];
#pragma unroll
for (int g = 0; g < G; ++g) { o0[g] += p[g] * k0; o1[g] += p[g] * k1; }
}
#pragma unroll
for (int g = 0; g < G; ++g) {
const size_t bi = ((size_t) t * heads + hg * G + g) * nsplit + chunk;
*(float2*) (part + bi * D + c) = make_float2(o0[g], o1[g]);
if (threadIdx.x == 0) { ml[bi * 2] = mloc[g]; ml[bi * 2 + 1] = lloc[g]; }
}
}
__global__ void __launch_bounds__(256) attn_merge(const float* __restrict__ part, const float* __restrict__ ml, const float* __restrict__ sink,
int heads, int nsplit, int R, AttnRows ar, float* __restrict__ out) {
constexpr int D = 512;
const int h = blockIdx.x, t = blockIdx.y;
const int total = ar.nwin[t] + ar.nsel[t];
const int ns = (total + R - 1) / R;
const size_t base = ((size_t) t * heads + h) * nsplit;
float M = sink[h];
for (int s = 0; s < ns; ++s) M = fmaxf(M, ml[(base + s) * 2]);
float den = __expf(sink[h] - M);
for (int s = 0; s < ns; ++s) den += ml[(base + s) * 2 + 1] * __expf(ml[(base + s) * 2] - M);
const int c = threadIdx.x * 2;
float a0 = 0.f, a1 = 0.f;
for (int s = 0; s < ns; ++s) {
const float w = __expf(ml[(base + s) * 2] - M);
const float2 v = *(const float2*) (part + (base + s) * D + c);
a0 += w * v.x;
a1 += w * v.y;
}
*(float2*) (out + ((size_t) t * heads + h) * D + c) = make_float2(a0 / den, a1 / den);
}
struct AttnSplitScratch {
float* part = nullptr; // [T][heads][nsplit][512]
float* ml = nullptr; // [T][heads][nsplit][2]
int nsplit = 0, max_t = 0;
};
// total_max = the largest nwin + nsel of the T queries
template <int G, int R>
void sparse_attn_split(const float* q, const uint16_t* win, const uint8_t* ckv, size_t ckv_row_bytes, const int* sel, int sel_stride,
const AttnRows& ar, const float* sink, int heads, int T, float scale, float* out, const AttnSplitScratch& sc,
int total_max, cudaStream_t s) {
const int nsplit = (total_max + R - 1) / R;
attn_part<G, R><<<dim3(heads / G, nsplit, T), 256, 0, s>>>(q, win, ckv, ckv_row_bytes, sel, sel_stride, ar, heads, scale, sc.part, sc.ml, sc.nsplit);
attn_merge<<<dim3(heads, T), 256, 0, s>>>(sc.part, sc.ml, sink, heads, sc.nsplit, R, ar, out);
}
} // namespace strata::ds4lab
+16
View File
@@ -0,0 +1,16 @@
#!/bin/bash
# build the kernel labs 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
CPU=../../src/kernels/cpu
INC="-I../../include -I../../third_party/ggml -I$CPU"
g++ -O2 -std=c++17 $INC -c ../trellis/tqenc.cpp -o out/tqenc.o
g++ -O2 -std=c++17 $INC -c $CPU/tq_cpu.cpp -o out/tq_cpu.o
g++ -O2 -std=c++17 $INC -mavx2 -mfma -mf16c -c $CPU/tq_avx2.cpp -o out/tq_avx2.o
g++ -O2 -std=c++17 $INC -mavx512f -mavx512bw -mavx512vl -mavx512vnni -mavx512vbmi -mavx2 -mfma -mf16c -c $CPU/tq_avx512.cpp -o out/tq_avx512.o
$NVCC -O3 -std=c++17 -arch=$ARCH -lineinfo -I../../include -o out/tqk_lab tqk_lab.cu out/tqenc.o out/tq_cpu.o out/tq_avx2.o out/tq_avx512.o -lpthread
# DeepSeek kernel lab: links src/dsv41/ds4_kernels.cu unmodified
$NVCC -O3 -std=c++17 -arch=$ARCH -lineinfo -I../../include -o out/ds4_lab ds4_lab.cu ../../src/dsv41/ds4_kernels.cu
+34
View File
@@ -0,0 +1,34 @@
// tools/dsv41_lab/code_sqnr.cpp - weight SQNR of the trellis encoder on N(0,1) blocks for a codebook chosen by TQE_CODE
// (unset = the shipped table). TQE_CODE=3sum ./code_sqnr [type 224] [blocks 16384] [thorough 0|1]
// Rate-distortion limit of a Gaussian at K bits per 4 weights: 6.02 K / 4 dB.
#include "../trellis/tqenc.hpp"
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <random>
#include <vector>
int main(int argc, char** argv) {
const int type = argc > 1 ? std::atoi(argv[1]) : 224;
const int64_t nb = argc > 2 ? std::atoll(argv[2]) : 16384;
const bool thorough = argc > 3 && std::atoi(argv[3]);
const int K = tqenc::type_kbits(type);
std::mt19937_64 rng(12345);
std::normal_distribution<float> nd(0.f, 1.f);
std::vector<float> w((size_t) nb * 128);
for (auto& v : w) v = nd(rng);
std::vector<uint8_t> enc((size_t) nb * tqenc::block_bytes(type));
tqenc::Params p;
if (thorough) { p.iters = 3; p.ncand = 3; p.scale_tries = 3; }
int64_t nonfinite = 0, zero = 0;
tqenc::encode_blocks(type, w.data(), nullptr, nb, enc.data(), p, 0, nullptr, &nonfinite, &zero);
std::vector<float> dec((size_t) nb * 128);
tqenc::decode_blocks(type, enc.data(), nb, dec.data());
double sq = 0, ee = 0;
for (size_t i = 0; i < w.size(); ++i) { sq += (double) w[i] * w[i]; ee += (double) (dec[i] - w[i]) * (dec[i] - w[i]); }
const double sqnr = 10 * std::log10(sq / ee), lim = 6.0206 * K / 4.0;
std::printf("TQE_CODE=%-8s type %d K=%d %s: SQNR %.3f dB, limit %.3f dB, gap %.3f dB (rel MSE %.4f)\n", std::getenv("TQE_CODE") ? std::getenv("TQE_CODE") : "table", type, K,
thorough ? "thorough" : "fast", sqnr, lim, lim - sqnr, ee / sq);
return 0;
}
+84
View File
@@ -0,0 +1,84 @@
// tools/dsv41_lab/computed_codes.hpp - LUT-free ("computed") codebooks for the 15-bit-state, 4-weights-a-step trellis, after
// QTIP (Tseng et al., Cornell-RelaxML/qtip lib/codebook/bitshift.py): 1MAD and 3INST decode a state with a 32-bit LCG and a few
// bit tricks instead of a table. QTIP emits one weight per LCG word (V = 1); a step of our format has four weights, so every
// variant here uses 2 to 4 LCG words per state. Host-side definition (the encoder takes it through the TQE_CODE environment
// variable, tools/trellis/tqenc.cpp) and the CUDA kernels use the same constants (tqk_gemv_c.cuh).
#pragma once
#include <cmath>
#include <cstdint>
#include <cstdlib>
#include <cstring>
namespace tqcode {
// LCG words of a state: x_i = s * kA[i] + kB[i]
inline constexpr uint32_t kA[4] = {89226354u, 0x9E3779B1u, 0x85EBCA6Bu, 0xC2B2AE35u};
inline constexpr uint32_t kB[4] = {64248484u, 0x7F4A7C15u, 0x165667B1u, 0x27D4EB2Fu};
inline constexpr uint32_t kMask3 = 0x8FFF8FFFu, kXor3 = 0x3B603B60u; // QTIP 3INST: (x & 0x8FFF8FFF) ^ 0x3B603B60 = two fp16
inline float h2f(uint16_t h) {
const uint32_t sign = (uint32_t) (h & 0x8000u) << 16;
const uint32_t e = (h >> 10) & 0x1fu, m = h & 0x3ffu;
float f;
if (e == 0) f = std::ldexp((float) m, -24);
else if (e == 31) f = INFINITY;
else f = std::ldexp(1.0f + m / 1024.0f, (int) e - 15);
return sign ? -f : f;
}
// float -> fp16 -> float, round to nearest even (what HADD2 does to the exact sum of two fp16 values)
inline float rn16(float x) {
if (x == 0.0f) return x;
int e;
std::frexp(x, &e); // |x| in [2^(e-1), 2^e)
const int q = (e - 1 < -14 ? -14 : e - 1) - 10;
const float quantum = std::ldexp(1.0f, q);
return std::nearbyint(x / quantum) * quantum;
}
inline uint32_t word3(uint32_t s, int i) { return ((s * kA[i] + kB[i]) & kMask3) ^ kXor3; }
enum Kind { kNone = 0, k1mad, k3inst, k3sum, k3single };
inline Kind kind_of(const char* n) {
if (!n || !*n) return kNone;
if (!std::strcmp(n, "1mad")) return k1mad;
if (!std::strcmp(n, "3inst")) return k3inst;
if (!std::strcmp(n, "3sum")) return k3sum;
if (!std::strcmp(n, "3single")) return k3single;
return kNone;
}
// the four (unnormalised) weights of state s
inline void code4(Kind k, uint32_t s, float out[4]) {
s &= 0x7fffu;
switch (k) {
case k1mad:
for (int i = 0; i < 4; ++i) {
const uint32_t x = s * kA[i] + kB[i];
const int y = (int) (x & 255) + (int) ((x >> 8) & 255) + (int) ((x >> 16) & 255) + (int) (x >> 24);
out[i] = (float) (y - 510) / 147.800537109375f;
}
break;
case k3inst:
for (int i = 0; i < 4; ++i) { const uint32_t r = word3(s, i); out[i] = rn16(h2f((uint16_t) (r >> 16)) + h2f((uint16_t) (r & 0xffffu))); }
break;
case k3sum: {
const uint32_t r0 = word3(s, 0), r1 = word3(s, 1), r2 = word3(s, 2), r3 = word3(s, 3);
out[0] = rn16(h2f((uint16_t) (r0 & 0xffffu)) + h2f((uint16_t) (r1 & 0xffffu)));
out[1] = rn16(h2f((uint16_t) (r0 >> 16)) + h2f((uint16_t) (r1 >> 16)));
out[2] = rn16(h2f((uint16_t) (r2 & 0xffffu)) + h2f((uint16_t) (r3 & 0xffffu)));
out[3] = rn16(h2f((uint16_t) (r2 >> 16)) + h2f((uint16_t) (r3 >> 16)));
break;
}
default: {
const uint32_t r0 = word3(s, 0), r1 = word3(s, 1);
out[0] = h2f((uint16_t) (r0 & 0xffffu));
out[1] = h2f((uint16_t) (r0 >> 16));
out[2] = h2f((uint16_t) (r1 & 0xffffu));
out[3] = h2f((uint16_t) (r1 >> 16));
}
}
}
} // namespace tqcode
+392
View File
@@ -0,0 +1,392 @@
// tools/dsv41_lab/ds4_lab.cu - parity + speed of the DeepSeek-V4.1 device kernels (src/dsv41/ds4_kernels.cu, the file the port
// ports, linked unmodified) on synthetic tensors at the real shapes: dim 5120, hc 4 (mHC 24 x 20480, 20 Sinkhorn iterations),
// 64 heads x 512 (MQA, K = V), 128-row window + sink, top-512 compressed rows (E2M1 + E4M3 scales), indexer 32 x 128,
// router 384 / 6, Engram rows 256 (FP8 + E8M0). References are plain double-precision C++ written from the kernels' documented
// math (DeepSeek model.py), not from the kernels.
// ds4_lab [--tokens 1,2,3,4,5] [--only name,name] [--ctx 8192] [--reps 100]
#include "../../src/dsv41/ds4_kernels.cuh"
#include "attn_split.cuh"
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <functional>
#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 strata::ds4;
static uint64_t g_rng = 0x2545f4914f6cdd1dull;
static uint64_t rnd() { g_rng ^= g_rng << 13; g_rng ^= g_rng >> 7; g_rng ^= g_rng << 17; return g_rng; }
static float urand() { return (float) ((rnd() >> 40) * (1.0 / 16777216.0)); } // [0, 1)
static float srand_() { return urand() * 2.f - 1.f; } // [-1, 1)
static float nrand() { float u = 0; for (int i = 0; i < 12; ++i) u += urand(); return u - 6.f; }
static cudaStream_t g_s;
static int g_fails = 0;
static int g_reps = 100;
template <class T> struct Dev {
T* p = nullptr; size_t n = 0;
Dev() {}
explicit Dev(const std::vector<T>& h) { set(h); }
void set(const std::vector<T>& h) { if (p) cudaFree(p); n = h.size(); CK(cudaMalloc(&p, std::max<size_t>(n, 1) * sizeof(T))); CK(cudaMemcpy(p, h.data(), n * sizeof(T), cudaMemcpyHostToDevice)); }
void alloc(size_t cnt) { if (p) cudaFree(p); n = cnt; CK(cudaMalloc(&p, std::max<size_t>(n, 1) * sizeof(T))); CK(cudaMemset(p, 0, n * sizeof(T))); }
std::vector<T> get() const { std::vector<T> h(n); CK(cudaMemcpy(h.data(), p, n * sizeof(T), cudaMemcpyDeviceToHost)); return h; }
~Dev() { if (p) cudaFree(p); }
};
static uint16_t f2bf(float f) { uint32_t u; std::memcpy(&u, &f, 4); u += 0x7fffu + ((u >> 16) & 1u); return (uint16_t) (u >> 16); }
static float bf2f(uint16_t b) { uint32_t u = (uint32_t) b << 16; float f; std::memcpy(&f, &u, 4); return f; }
static float e4m3_val(uint8_t q) {
const int e = (q >> 3) & 15, m = q & 7; float v;
if (e == 15 && m == 7) v = NAN; else if (e == 0) v = m * (1.f / 512.f); else v = std::ldexp(1.f + m / 8.f, e - 7);
return (q & 0x80) ? -v : v;
}
static const float kE2m1[8] = {0.f, 0.5f, 1.f, 1.5f, 2.f, 3.f, 4.f, 6.f};
static float e2m1_val(int c) { return (c & 8) ? -kE2m1[c & 7] : kE2m1[c & 7]; }
// ---- timing: n launches of `fn` captured into a graph (no launch gaps), replayed
static double time_us(const std::function<void()>& fn) {
cudaGraph_t g; cudaGraphExec_t ge;
const int inner = 20;
CK(cudaStreamBeginCapture(g_s, cudaStreamCaptureModeGlobal));
for (int i = 0; i < inner; ++i) fn();
CK(cudaStreamEndCapture(g_s, &g));
CK(cudaGraphInstantiate(&ge, g, 0));
CK(cudaGraphLaunch(ge, g_s)); CK(cudaStreamSynchronize(g_s));
cudaEvent_t e0, e1; cudaEventCreate(&e0); cudaEventCreate(&e1);
const int outer = std::max(1, g_reps / inner);
cudaEventRecord(e0, g_s);
for (int i = 0; i < outer; ++i) CK(cudaGraphLaunch(ge, g_s));
cudaEventRecord(e1, g_s); CK(cudaEventSynchronize(e1));
float ms; cudaEventElapsedTime(&ms, e0, e1);
cudaGraphExecDestroy(ge); cudaGraphDestroy(g);
return ms * 1e3 / (outer * inner);
}
static void report(const char* name, int T, double err, double tol, double us, const char* extra = "") {
const bool ok = err <= tol;
g_fails += !ok;
std::printf("%-22s T=%-2d err %.2e (tol %.0e) %-4s %9.2f us %s\n", name, T, err, tol, ok ? "ok" : "FAIL", us, extra);
}
static double max_rel(const std::vector<float>& got, const std::vector<double>& ref) { // max |got-ref| / (max|ref| + tiny)
double mx = 0, e = 0;
for (double r : ref) mx = std::max(mx, std::fabs(r));
for (size_t i = 0; i < ref.size(); ++i) e = std::max(e, std::fabs(got[i] - ref[i]));
return e / (mx + 1e-30);
}
// ============================================================================================================ mHC
static void test_mhc(int T) {
const int dim = 5120, hc = 4, hcdim = hc * dim, n_mix = 24, iters = 20;
const float eps = 1e-6f, hc_eps = 1e-6f;
std::vector<float> h((size_t) T * hcdim), fn((size_t) n_mix * hcdim), scale = {0.3f, 0.5f, 0.7f}, base(24);
for (auto& v : h) v = nrand();
for (auto& v : fn) v = nrand() * 0.01f;
for (auto& v : base) v = srand_();
Dev<float> dh(h), dfn(fn), dscale(scale), dbase(base), dmix, dpre, dpost, dcomb;
dmix.alloc((size_t) T * 32); dpre.alloc((size_t) T * 8); dpost.alloc((size_t) T * 8); dcomb.alloc((size_t) T * 64);
// hc_mix
hc_mix(dh.p, dfn.p, hcdim, n_mix, T, eps, dmix.p, g_s); CK(cudaStreamSynchronize(g_s));
auto mix = dmix.get();
std::vector<double> rmix((size_t) T * 32, 0.0), gm((size_t) T * 32, 0.0);
for (int t = 0; t < T; ++t) {
double ss = 0; for (int k = 0; k < hcdim; ++k) ss += (double) h[(size_t) t * hcdim + k] * h[(size_t) t * hcdim + k];
const double inv = 1.0 / std::sqrt(ss / hcdim + eps);
for (int m = 0; m < n_mix; ++m) { double a = 0; for (int k = 0; k < hcdim; ++k) a += (double) h[(size_t) t * hcdim + k] * fn[(size_t) m * hcdim + k]; rmix[(size_t) t * 32 + m] = a * inv; gm[(size_t) t * 32 + m] = mix[(size_t) t * 32 + m]; }
}
std::vector<float> mixg(mix.begin(), mix.end());
{ std::vector<double> r2; std::vector<float> g2; for (int t = 0; t < T; ++t) for (int m = 0; m < n_mix; ++m) { r2.push_back(rmix[(size_t) t * 32 + m]); g2.push_back(mix[(size_t) t * 32 + m]); }
report("hc_mix", T, max_rel(g2, r2), 1e-5, time_us([&] { hc_mix(dh.p, dfn.p, hcdim, n_mix, T, eps, dmix.p, g_s); }), "24 x 20480 dots + norm"); }
// hc_split (Sinkhorn)
hc_split(dmix.p, dscale.p, dbase.p, hc, iters, hc_eps, T, dpre.p, dpost.p, dcomb.p, g_s); CK(cudaStreamSynchronize(g_s));
auto pre = dpre.get(), post = dpost.get(), comb = dcomb.get();
{
std::vector<double> rr; std::vector<float> gg;
for (int t = 0; t < T; ++t) {
const float* mx = mix.data() + (size_t) t * 32;
for (int k = 0; k < hc; ++k) { rr.push_back(1.0 / (1.0 + std::exp(-((double) mx[k] * scale[0] + base[k]))) + hc_eps); gg.push_back(pre[(size_t) t * 8 + k]); }
for (int k = 0; k < hc; ++k) { rr.push_back(2.0 / (1.0 + std::exp(-((double) mx[hc + k] * scale[1] + base[hc + k])))); gg.push_back(post[(size_t) t * 8 + k]); }
double c[4][4];
for (int j = 0; j < 4; ++j) { double m = -1e300; for (int k = 0; k < 4; ++k) { c[j][k] = (double) mx[8 + j * 4 + k] * scale[2] + base[8 + j * 4 + k]; m = std::max(m, c[j][k]); }
double s = 0; for (int k = 0; k < 4; ++k) { c[j][k] = std::exp(c[j][k] - m); s += c[j][k]; } for (int k = 0; k < 4; ++k) c[j][k] = c[j][k] / s + hc_eps; }
auto colnorm = [&] { for (int k = 0; k < 4; ++k) { double s = 0; for (int j = 0; j < 4; ++j) s += c[j][k]; for (int j = 0; j < 4; ++j) c[j][k] /= s + hc_eps; } };
auto rownorm = [&] { for (int j = 0; j < 4; ++j) { double s = 0; for (int k = 0; k < 4; ++k) s += c[j][k]; for (int k = 0; k < 4; ++k) c[j][k] /= s + hc_eps; } };
colnorm();
for (int it = 1; it < iters; ++it) { rownorm(); colnorm(); }
for (int j = 0; j < 4; ++j) for (int k = 0; k < 4; ++k) { rr.push_back(c[j][k]); gg.push_back(comb[(size_t) t * 64 + j * 4 + k]); }
}
report("hc_split sinkhorn", T, max_rel(gg, rr), 2e-5, time_us([&] { hc_split(dmix.p, dscale.p, dbase.p, hc, iters, hc_eps, T, dpre.p, dpost.p, dcomb.p, g_s); }), "20 iterations");
}
// hc_pre_norm: x = rmsnorm(sum_s pre[s] h[s]) * w
std::vector<float> w(dim); for (auto& v : w) v = 0.5f + urand();
Dev<float> dw(w), dx; dx.alloc((size_t) T * dim);
hc_pre_norm(dh.p, dpre.p, dw.p, dim, hc, T, eps, dx.p, g_s); CK(cudaStreamSynchronize(g_s));
{
auto x = dx.get(); std::vector<double> rr; std::vector<float> gg;
for (int t = 0; t < T; ++t) {
std::vector<double> a(dim); double ss = 0;
for (int e = 0; e < dim; ++e) { double s = 0; for (int k = 0; k < hc; ++k) s += (double) pre[(size_t) t * 8 + k] * h[((size_t) t * hc + k) * dim + e]; a[e] = s; ss += s * s; }
const double inv = 1.0 / std::sqrt(ss / dim + eps);
for (int e = 0; e < dim; ++e) { rr.push_back(a[e] * inv * w[e]); gg.push_back(x[(size_t) t * dim + e]); }
}
report("hc_pre_norm", T, max_rel(gg, rr), 2e-5, time_us([&] { hc_pre_norm(dh.p, dpre.p, dw.p, dim, hc, T, eps, dx.p, g_s); }));
}
// hc_post / hc_post_inplace: out[k][e] = post[k] y[e] + sum_j comb[j][k] res[j][e]
std::vector<float> y((size_t) T * dim); for (auto& v : y) v = nrand();
Dev<float> dy(y), dout; dout.alloc((size_t) T * hcdim);
hc_post(dy.p, dh.p, dpost.p, dcomb.p, dim, hc, T, dout.p, g_s); CK(cudaStreamSynchronize(g_s));
{
auto o = dout.get(); std::vector<double> rr; std::vector<float> gg;
for (int t = 0; t < T; ++t) for (int k = 0; k < hc; ++k) for (int e = 0; e < dim; ++e) {
double a = (double) post[(size_t) t * 8 + k] * y[(size_t) t * dim + e];
for (int j = 0; j < hc; ++j) a += (double) comb[(size_t) t * 64 + j * hc + k] * h[((size_t) t * hc + j) * dim + e];
rr.push_back(a); gg.push_back(o[((size_t) t * hc + k) * dim + e]);
}
const double err = max_rel(gg, rr);
report("hc_post", T, err, 2e-6, time_us([&] { hc_post(dy.p, dh.p, dpost.p, dcomb.p, dim, hc, T, dout.p, g_s); }));
Dev<float> dh2(h);
hc_post_inplace(dy.p, dh2.p, dpost.p, dcomb.p, dim, hc, T, g_s); CK(cudaStreamSynchronize(g_s));
auto o2 = dh2.get(); std::vector<float> gg2(o2.begin(), o2.begin() + (size_t) T * hcdim);
report("hc_post_inplace", T, max_rel(gg2, rr), 2e-6, time_us([&] { hc_post_inplace(dy.p, dh2.p, dpost.p, dcomb.p, dim, hc, T, g_s); }), "(timing re-applies in place)");
}
}
// ============================================================================================================ router
static void test_router(int T) {
const int n = 384, k = 6; const float rs = 1.5f;
std::vector<float> logits((size_t) T * 1024, 0.f), bias(n);
for (int t = 0; t < T; ++t) for (int i = 0; i < n; ++i) logits[(size_t) t * 1024 + i] = nrand() * 2.f;
for (auto& v : bias) v = srand_() * 0.3f;
Dev<float> dl(logits), db(bias), dw; Dev<int> di; dw.alloc((size_t) T * kPicks); di.alloc((size_t) T * kPicks);
route(dl.p, db.p, n, k, T, rs, di.p, dw.p, g_s); CK(cudaStreamSynchronize(g_s));
auto gi = di.get(); auto gw = dw.get();
int bad_idx = 0; std::vector<double> rr; std::vector<float> gg;
for (int t = 0; t < T; ++t) {
std::vector<double> sc(n), bs(n);
for (int i = 0; i < n; ++i) { const double l = logits[(size_t) t * 1024 + i]; sc[i] = std::sqrt(l > 20 ? l : std::log1p(std::exp(l))); bs[i] = sc[i] + bias[i]; }
std::vector<int> ord(n); for (int i = 0; i < n; ++i) ord[i] = i;
std::partial_sort(ord.begin(), ord.begin() + k, ord.end(), [&](int a, int b) { return bs[a] > bs[b] || (bs[a] == bs[b] && a < b); });
double s = 0; for (int r = 0; r < k; ++r) s += sc[ord[r]];
for (int r = 0; r < k; ++r) { bad_idx += gi[(size_t) t * kPicks + r] != ord[r]; rr.push_back(sc[ord[r]] / (s + 1e-20) * rs); gg.push_back(gw[(size_t) t * kPicks + r]); }
}
char ex[64]; std::snprintf(ex, sizeof ex, "%d / %d picks differ", bad_idx, T * k);
report("route (sqrt-softplus)", T, bad_idx ? 1.0 : max_rel(gg, rr), 1e-5, time_us([&] { route(dl.p, db.p, n, k, T, rs, di.p, dw.p, g_s); }), ex);
}
// ============================================================================================================ compressor
static void test_compress(int T, int ratio) {
const int d = 512; const float eps = 1e-6f;
// state pre-filled for the slots before p0; p0 chosen so that the last token of the window completes a group
const int p0 = ratio * 3 + (ratio - T);
std::vector<float> kv((size_t) T * d), sc((size_t) T * d), kst((size_t) ratio * d), sst((size_t) ratio * d), w(d);
for (auto& v : kv) v = nrand(); for (auto& v : sc) v = nrand() * 2.f; for (auto& v : kst) v = nrand(); for (auto& v : sst) v = nrand() * 2.f;
for (auto& v : w) v = 0.5f + urand();
Dev<float> dkv(kv), dsc(sc), dk(kst), ds(sst), dw(w), dlat; dlat.alloc((size_t) d * 2);
compress_win(dkv.p, dsc.p, dk.p, ds.p, ratio, p0, T, d, dw.p, eps, dlat.p, g_s); CK(cudaStreamSynchronize(g_s));
auto lat = dlat.get();
// reference: slots (p0+t)%ratio overwritten by the window's tokens, group = all `ratio` slots
std::vector<float> k2 = kst, s2 = sst;
for (int t = 0; t < T; ++t) { const int slot = (p0 + t) % ratio; for (int e = 0; e < d; ++e) { k2[(size_t) slot * d + e] = kv[(size_t) t * d + e]; s2[(size_t) slot * d + e] = sc[(size_t) t * d + e]; } }
std::vector<double> rr(d); double ss = 0;
for (int e = 0; e < d; ++e) { double m = -1e300; for (int s = 0; s < ratio; ++s) m = std::max(m, (double) s2[(size_t) s * d + e]);
double den = 0; for (int s = 0; s < ratio; ++s) den += std::exp(s2[(size_t) s * d + e] - m);
double a = 0; for (int s = 0; s < ratio; ++s) a += (double) k2[(size_t) s * d + e] * std::exp(s2[(size_t) s * d + e] - m) / den; rr[e] = a; ss += a * a; }
const double inv = 1.0 / std::sqrt(ss / d + eps); for (int e = 0; e < d; ++e) rr[e] = rr[e] * inv * w[e];
char nm[32]; std::snprintf(nm, sizeof nm, "compress_win r=%d", ratio);
std::vector<float> gg(lat.begin(), lat.begin() + d);
report(nm, T, max_rel(gg, rr), 5e-6, time_us([&] { compress_win(dkv.p, dsc.p, dk.p, ds.p, ratio, p0, T, d, dw.p, eps, dlat.p, g_s); }), "d 512, pooling window");
}
// ============================================================================================================ indexer
static void test_indexer(int T, int n) {
const int heads = 32, hd = 128, topk_k = 512;
const size_t rb = kv_row_bytes(kKvFp4p, hd);
std::vector<uint8_t> keys((size_t) n * rb, 0);
std::vector<float> kdec((size_t) n * hd);
for (int p = 0; p < n; ++p) {
uint8_t* r = &keys[(size_t) p * rb];
for (int j = 0; j < hd / 2; ++j) r[j] = (uint8_t) (rnd() & 0xff);
for (int g = 0; g < hd / 32; ++g) r[hd / 2 + g] = (uint8_t) (120 + (rnd() % 5)); // 2^-7 .. 2^-3
for (int e = 0; e < hd; ++e) { const int code = (r[e / 2] >> (4 * (e & 1))) & 15; kdec[(size_t) p * hd + e] = e2m1_val(code) * std::ldexp(1.f, (int) r[hd / 2 + e / 32] - 127); }
}
std::vector<float> q((size_t) T * heads * hd), w((size_t) T * 64, 0.f);
for (auto& v : q) v = nrand(); for (int t = 0; t < T; ++t) for (int h = 0; h < heads; ++h) w[(size_t) t * 64 + h] = srand_();
Dev<uint8_t> dk(keys); Dev<float> dq(q), dw(w), dout; dout.alloc((size_t) T * n);
Rows lim; for (int t = 0; t < kWin; ++t) { lim.n[t] = n; lim.k[t] = topk_k; }
index_score(dq.p, dw.p, dk.p, heads, hd, T, n, nullptr, 0, 1, lim, dout.p, n, g_s); CK(cudaStreamSynchronize(g_s));
auto sc = dout.get();
std::vector<double> rr; std::vector<float> gg;
for (int t = 0; t < T; ++t) for (int p = 0; p < n; p += std::max(1, n / 512)) {
double s = 0; for (int h = 0; h < heads; ++h) { double a = 0; for (int e = 0; e < hd; ++e) a += (double) q[((size_t) t * heads + h) * hd + e] * kdec[(size_t) p * hd + e]; s += std::max(a, 0.0) * w[(size_t) t * 64 + h]; }
rr.push_back(s); gg.push_back(sc[(size_t) t * n + p]);
}
char ex[96]; std::snprintf(ex, sizeof ex, "%d keys, %.1f MB of keys", n, n * (double) rb / 1e6);
const double us = time_us([&] { index_score(dq.p, dw.p, dk.p, heads, hd, T, n, nullptr, 0, 1, lim, dout.p, n, g_s); });
report("index_score", T, max_rel(gg, rr), 3e-5, us, ex);
// top-512 of the device's own scores: exact set compare
Rows tr; for (int t = 0; t < kWin; ++t) { tr.n[t] = n; tr.k[t] = std::min(topk_k, n); }
Dev<int> dsel; dsel.alloc((size_t) T * topk_k);
topk(dout.p, n, T, tr, nullptr, 0, 1, dsel.p, topk_k, g_s); CK(cudaStreamSynchronize(g_s));
auto sel = dsel.get(); int bad = 0;
for (int t = 0; t < T; ++t) {
std::vector<int> ord(n); for (int i = 0; i < n; ++i) ord[i] = i;
std::nth_element(ord.begin(), ord.begin() + topk_k, ord.end(), [&](int a, int b) { return sc[(size_t) t * n + a] > sc[(size_t) t * n + b]; });
std::vector<char> in(n, 0); for (int i = 0; i < topk_k; ++i) in[ord[i]] = 1;
const float kth = sc[(size_t) t * n + *std::min_element(ord.begin(), ord.begin() + topk_k, [&](int a, int b) { return sc[(size_t) t * n + a] < sc[(size_t) t * n + b]; })];
for (int i = 0; i < topk_k; ++i) { const int p = sel[(size_t) t * topk_k + i]; if (p < 0 || p >= n || (!in[p] && sc[(size_t) t * n + p] != kth)) ++bad; }
}
std::snprintf(ex, sizeof ex, "%d wrong picks of %d", bad, T * topk_k);
report("topk 512", T, bad ? 1.0 : 0.0, 0.0, time_us([&] { topk(dout.p, n, T, tr, nullptr, 0, 1, dsel.p, topk_k, g_s); }), ex);
}
// ============================================================================================================ attention
static void test_attn(int T, int ncache) {
const int heads = 64, d = 512, nwin = 128, nsel = 512;
const float scale = 1.f / std::sqrt((float) d);
const size_t rb = kv_row_bytes(kKvFp4, d); // 304
std::vector<uint8_t> ckv((size_t) ncache * rb, 0);
std::vector<float> cdec((size_t) ncache * d);
for (int p = 0; p < ncache; ++p) {
uint8_t* r = &ckv[(size_t) p * rb];
for (int j = 0; j < d / 2; ++j) r[j] = (uint8_t) (rnd() & 0xff);
for (int g = 0; g < d / 16; ++g) r[d / 2 + g] = (uint8_t) ((7 << 3) | (rnd() & 7)) - (uint8_t) (rnd() % 3 * 8); // ~1 .. 0.25
for (int e = 0; e < d; ++e) { const int code = (r[e / 2] >> (4 * (e & 1))) & 15; cdec[(size_t) p * d + e] = e2m1_val(code) * e4m3_val(r[d / 2 + e / 16]); }
}
// window buffer: nwin + T - 1 rows (each query sees nwin of them)
const int wrows = nwin + T;
std::vector<uint16_t> win((size_t) wrows * d); std::vector<float> wdec((size_t) wrows * d);
for (size_t i = 0; i < win.size(); ++i) { win[i] = f2bf(nrand()); wdec[i] = bf2f(win[i]); }
std::vector<float> q((size_t) T * heads * d), sink(heads);
for (auto& v : q) v = nrand(); for (auto& v : sink) v = srand_();
std::vector<int> sel((size_t) T * nsel);
for (int t = 0; t < T; ++t) for (int i = 0; i < nsel; ++i) sel[(size_t) t * nsel + i] = (int) (rnd() % ncache);
AttnRows ar; for (int t = 0; t < kWin; ++t) { ar.win0[t] = t < T ? t + 1 : 0; ar.nwin[t] = nwin; ar.nsel[t] = nsel; }
Dev<uint8_t> dck(ckv); Dev<uint16_t> dwin(win); Dev<float> dq(q), dsink(sink), dout; Dev<int> dsel(sel); dout.alloc((size_t) T * heads * d);
Dev<uint16_t> dscr; dscr.alloc((size_t) kAttnScratchT * (nsel + 8) * d);
AttnScratch scr; scr.rows = dscr.p; scr.max_t = kAttnScratchT; scr.cap = nsel + 8;
sparse_attn(dq.p, dwin.p, dck.p, dsel.p, nsel, ar, dsink.p, heads, d, T, scale, dout.p, g_s, kKvFp4, 0, &scr); CK(cudaStreamSynchronize(g_s));
auto o = dout.get(); std::vector<double> rr; std::vector<float> gg;
for (int t = 0; t < T; t += std::max(1, T / 2)) for (int h = 0; h < heads; h += 7) {
std::vector<double> s; std::vector<const float*> rows;
for (int j = 0; j < nwin; ++j) rows.push_back(&wdec[(size_t) (ar.win0[t] + j) * d]);
for (int i = 0; i < nsel; ++i) rows.push_back(&cdec[(size_t) sel[(size_t) t * nsel + i] * d]);
double m = sink[h];
for (auto* rw : rows) { double a = 0; for (int e = 0; e < d; ++e) a += (double) q[((size_t) t * heads + h) * d + e] * rw[e]; s.push_back(a * scale); m = std::max(m, s.back()); }
double den = std::exp(sink[h] - m); for (double v : s) den += std::exp(v - m);
std::vector<double> acc(d, 0.0);
for (size_t j = 0; j < rows.size(); ++j) { const double p = std::exp(s[j] - m) / den; for (int e = 0; e < d; ++e) acc[e] += p * rows[j][e]; }
for (int e = 0; e < d; ++e) { rr.push_back(acc[e]); gg.push_back(o[((size_t) t * heads + h) * d + e]); }
}
char ex[96]; std::snprintf(ex, sizeof ex, "64 heads x 512, 128 win + 512 sel, cache %d rows", ncache);
report("sparse_attn (fp4 ckv)", T, max_rel(gg, rr), 1e-4, time_us([&] { sparse_attn(dq.p, dwin.p, dck.p, dsel.p, nsel, ar, dsink.p, heads, d, T, scale, dout.p, g_s, kKvFp4, 0, &scr); }), ex);
// split-KV version (tools/dsv41_lab/attn_split.cuh), same inputs
{
const int total = nwin + nsel;
auto run = [&](const char* nm, auto launch_fn, int R) {
const int nsplit = (total + R - 1) / R;
Dev<float> part, ml; part.alloc((size_t) T * heads * nsplit * d); ml.alloc((size_t) T * heads * nsplit * 2);
strata::ds4lab::AttnSplitScratch ss; ss.part = part.p; ss.ml = ml.p; ss.nsplit = nsplit; ss.max_t = T;
Dev<float> o3; o3.alloc((size_t) T * heads * d);
auto go = [&] { launch_fn(dq.p, dwin.p, dck.p, rb, dsel.p, nsel, ar, dsink.p, heads, T, scale, o3.p, ss, total, g_s); };
go(); CK(cudaStreamSynchronize(g_s)); CK(cudaGetLastError());
auto oo = o3.get(); std::vector<float> g3;
for (int t = 0; t < T; t += std::max(1, T / 2)) for (int h = 0; h < heads; h += 7) for (int e = 0; e < d; ++e) g3.push_back(oo[((size_t) t * heads + h) * d + e]);
report(nm, T, max_rel(g3, rr), 1e-4, time_us(go), ex);
};
run("attn_split G4 R40", [](auto... a) { strata::ds4lab::sparse_attn_split<4, 40>(a...); }, 40);
run("attn_split G8 R40", [](auto... a) { strata::ds4lab::sparse_attn_split<8, 40>(a...); }, 40);
run("attn_split G4 R20", [](auto... a) { strata::ds4lab::sparse_attn_split<4, 20>(a...); }, 20);
run("attn_split G2 R32", [](auto... a) { strata::ds4lab::sparse_attn_split<2, 32>(a...); }, 32);
}
// the packed-rows kernel (no scratch): used from 8 queries on, timed here at this T for comparison
sparse_attn(dq.p, dwin.p, dck.p, dsel.p, nsel, ar, dsink.p, heads, d, T, scale, dout.p, g_s, kKvFp4, 0, nullptr); CK(cudaStreamSynchronize(g_s));
{ auto o2 = dout.get(); std::vector<float> g2; for (int t = 0; t < T; t += std::max(1, T / 2)) for (int h = 0; h < heads; h += 7) for (int e = 0; e < d; ++e) g2.push_back(o2[((size_t) t * heads + h) * d + e]);
report("sparse_attn (packed)", T, max_rel(g2, rr), 1e-4, time_us([&] { sparse_attn(dq.p, dwin.p, dck.p, dsel.p, nsel, ar, dsink.p, heads, d, T, scale, dout.p, g_s, kKvFp4, 0, nullptr); })); }
}
// ============================================================================================================ Engram
static void test_engram(int T) {
const int cols = 24, hd = 256, hc = 4, dim = 5120; const float eps = 1e-6f;
// dequant: n rows FP8 E4M3 + E8M0 scales
const int n = T * cols;
std::vector<uint8_t> rows((size_t) n * hd), scales((size_t) n * (hd / 32));
for (auto& v : rows) { do v = (uint8_t) (rnd() & 0xff); while ((v & 0x7f) == 0x7f); }
for (auto& v : scales) v = (uint8_t) (115 + rnd() % 8);
Dev<uint8_t> dr(rows), dsc(scales); Dev<float> dout; dout.alloc((size_t) n * hd);
engram_dequant(dr.p, dsc.p, n, hd, dout.p, g_s); CK(cudaStreamSynchronize(g_s));
auto o = dout.get(); size_t bad = 0;
for (int r = 0; r < n; ++r) for (int e = 0; e < hd; ++e) { const float ref = e4m3_val(rows[(size_t) r * hd + e]) * std::ldexp(1.f, (int) scales[(size_t) r * (hd / 32) + e / 32] - 127); if (std::memcmp(&ref, &o[(size_t) r * hd + e], 4) != 0) ++bad; }
char ex[64]; std::snprintf(ex, sizeof ex, "%zu of %zu values differ (bit exact)", bad, (size_t) n * hd);
report("engram_dequant", T, bad ? 1.0 : 0.0, 0.0, time_us([&] { engram_dequant(dr.p, dsc.p, n, hd, dout.p, g_s); }), ex);
// gate
std::vector<float> h((size_t) T * hc * dim), kv((size_t) T * (hc + 1) * dim), w((size_t) hc * dim);
for (auto& v : h) v = nrand(); for (auto& v : kv) v = nrand(); for (auto& v : w) v = 0.5f + urand();
Dev<float> dh(h), dkv(kv), dw(w);
engram_gate(dh.p, dkv.p, dw.p, hc, dim, T, eps, g_s); CK(cudaStreamSynchronize(g_s));
auto go = dh.get(); std::vector<double> rr; std::vector<float> gg;
for (int t = 0; t < T; ++t) for (int k = 0; k < hc; ++k) {
const float* hk = &h[((size_t) t * hc + k) * dim]; const float* key = &kv[(size_t) t * (hc + 1) * dim + (size_t) k * dim]; const float* val = &kv[(size_t) t * (hc + 1) * dim + (size_t) hc * dim];
double sh = 0, sk = 0, sd = 0; for (int e = 0; e < dim; ++e) { sh += (double) hk[e] * hk[e]; sk += (double) key[e] * key[e]; sd += (double) hk[e] * w[(size_t) k * dim + e] * key[e]; }
const double rstd = 1.0 / std::sqrt(sh / dim + eps) / std::sqrt(sk / dim + eps);
const double dot = sd * rstd / std::sqrt((double) dim); const double sq = std::copysign(std::sqrt(std::max(std::fabs(dot), 1e-6)), dot); const double gate = 1.0 / (1.0 + std::exp(-sq));
for (int e = 0; e < dim; ++e) { rr.push_back(hk[e] + gate * val[e]); gg.push_back(go[((size_t) t * hc + k) * dim + e]); }
}
Dev<float> dh2(h);
report("engram_gate", T, max_rel(gg, rr), 2e-6, time_us([&] { engram_gate(dh2.p, dkv.p, dw.p, hc, dim, T, eps, g_s); }), "(timing re-applies in place)");
// the n-gram row gather: 24 hash-picked rows of 256 per token = the host/SSD side; on the device only the gather of
// x rows (gather_rows) - T x 5120 floats
Gather gt; for (int i = 0; i < kWin * kPicks; ++i) gt.src[i] = (int) (rnd() % T);
Dev<float> dx; { std::vector<float> x((size_t) T * dim); for (auto& v : x) v = nrand(); dx.set(x); } Dev<float> dg; dg.alloc((size_t) T * kPicks * dim);
gather_rows(dx.p, gt, T * kPicks > kWin * kPicks ? kWin * kPicks : T * kPicks, dim, dg.p, g_s); CK(cudaStreamSynchronize(g_s));
auto go2 = dg.get(); size_t badg = 0; const int ng = std::min(T * kPicks, kWin * kPicks);
std::vector<float> xs = dx.get();
for (int r = 0; r < ng; ++r) for (int c = 0; c < dim; ++c) badg += go2[(size_t) r * dim + c] != xs[(size_t) gt.src[r] * dim + c];
std::snprintf(ex, sizeof ex, "%zu mismatches, %d rows", badg, ng);
report("gather_rows", T, badg ? 1.0 : 0.0, 0.0, time_us([&] { gather_rows(dx.p, gt, ng, dim, dg.p, g_s); }), ex);
}
// ============================================================================================================ swiglu + combine
static void test_swiglu(int T) {
const int n = T * 2304 * 6; const float lim = 10.f;
std::vector<float> g(n), u(n); for (auto& v : g) v = nrand() * 6.f; for (auto& v : u) v = nrand() * 6.f;
Dev<float> dg(g), du(u), dh; dh.alloc(n);
swiglu(dg.p, du.p, n, lim, dh.p, g_s); CK(cudaStreamSynchronize(g_s));
auto h = dh.get(); std::vector<double> rr; for (int i = 0; i < n; ++i) { const double gv = std::min((double) g[i], (double) lim), uv = std::min(std::max((double) u[i], -(double) lim), (double) lim); rr.push_back(gv / (1.0 + std::exp(-gv)) * uv); }
report("swiglu clamp 10", T, max_rel(h, rr), 3e-6, time_us([&] { swiglu(dg.p, du.p, n, lim, dh.p, g_s); }), "T x 6 experts x 2304");
}
int main(int argc, char** argv) {
std::vector<int> Ts = {1, 2, 3, 4, 5};
std::string only; int ctx = 8192;
for (int i = 1; i < argc; ++i) {
std::string a = argv[i];
if (a == "--tokens" && i + 1 < argc) { Ts.clear(); for (const char* p = argv[++i]; *p;) { Ts.push_back(std::atoi(p)); while (*p && *p != ',') ++p; if (*p) ++p; } }
else if (a == "--only" && i + 1 < argc) only = std::string(",") + argv[++i] + ",";
else if (a == "--ctx" && i + 1 < argc) ctx = std::atoi(argv[++i]);
else if (a == "--reps" && i + 1 < argc) g_reps = std::atoi(argv[++i]);
else if (a == "--dev" && i + 1 < argc) CK(cudaSetDevice(std::atoi(argv[++i])));
}
cudaDeviceProp prop; int dev; CK(cudaGetDevice(&dev)); CK(cudaGetDeviceProperties(&prop, dev));
std::printf("device %s sm_%d%d; kernels: src/dsv41/ds4_kernels.cu unmodified; graph-replayed timings (no launch gaps)\n", prop.name, prop.major, prop.minor);
CK(cudaStreamCreate(&g_s));
const int ncache = ctx / 4; // compressed rows at ratio 4
auto want = [&](const char* n) { return only.empty() || only.find(std::string(",") + n + ",") != std::string::npos; };
for (int T : Ts) {
if (want("mhc")) test_mhc(T);
if (want("router")) test_router(T);
if (want("compress")) { test_compress(T, 4); test_compress(T, 128); }
if (want("indexer")) test_indexer(T, ncache);
if (want("attn")) test_attn(T, ncache);
if (want("engram")) test_engram(T);
if (want("swiglu")) test_swiglu(T);
std::printf("\n");
}
std::printf("%s (%d failures)\n", g_fails ? "FAILED" : "ALL PARITY OK", g_fails);
return g_fails ? 1 : 0;
}
+38
View File
@@ -0,0 +1,38 @@
# HIP port of the trellis GEMV (gfx1201, R9700) - recipe
State: `wmma_emu.hpp` (host, lane by lane) reproduces the double reference to 3e-8 for K4..K7, widths 1/3/5, table codebook and the
computed code `3single` (`wmma_emu_test`, no GPU needed). `tqk_gemv_wmma.hip.cpp` is its line-by-line HIP form. It was **not
compiled or run** anywhere. Do the steps in this order; each one is a hard stop if it fails.
1. **Layout probe** (30 s). `hipcc --offload-arch=gfx1201 -O2 hip/wmma_probe.hip.cpp -o wmma_probe && HIP_VISIBLE_DEVICES=<n> ./wmma_probe`.
It must print `layout as assumed`. The assumption (wave32, `__builtin_amdgcn_wmma_f32_16x16x16_f16_w32_gfx12`, 8 halves per lane for A and B,
8 floats for D, no replication between the two lane halves):
`A[m][k]` in lane `l`, element `j`: `m = l % 16, k = 8 * (l / 16) + j`; `B[k][n]`: `k = 8 * (l / 16) + j, n = l % 16`; `D[m][n]`: `m = 8 * (l / 16) + i, n = l % 16`.
If it does not match, change `wmma_emu.hpp` (the specification) and `wmma_emu_test` until it passes with the layout the probe found, then
mirror the change in the kernel. (gfx11 replicated A/B between the halves and striped D by `2 i + l / 16`; gfx12 does not, as far as the
LLVM documentation says, but nobody here has measured it.)
2. **Emulator test**: `g++ -O2 -std=c++17 -I third_party/ggml tools/dsv41_lab/wmma_emu_test.cpp tools/trellis/tqenc.cpp -o wmma_emu_test` (and with `TQE_CODE=3single`).
3. **Kernel**: the data flow, all of it in `wmma_emu.hpp::gemv_tqw`:
* *Why a new layout.* mma.m16n8k16 gives a lane 2 rows of A and 4 floats of D; WMMA gives a lane 1 row of A (8 consecutive k) and 8 rows of D.
So lane `l = r + 16 kg` owns row `r` of the tile and **16 consecutive steps** (`u = 0..15`, steps `t = 16 kg + u`) of every 128-weight block:
stream bits `[(16 - 16 kg) K, (32 - 16 kg) K)`. The two blocks of a pair give 2 chunks of `16 K` bits = `K` words per lane
(`words[((tile * NP + P) * K + j) * 32 + lane]`, coalesced). Scales `sc[((tile*NP+P)*16 + row)*2 + bk]`: a lane reads rows `8 kg..8 kg+7`.
The bytes are the same as the file layout; the permutation is done at load (a bit shuffle per lane, `repack_tqw`).
* *k order.* WMMA k-slot `(kg, j)` of mma `m` = weight `4 (16 kg + 2 m) + j` of the block (steps `u = 2m, 2m+1` of the lane). A and B must use the same
map; B lane `(n, kg)` loads `x[n][blk*128 + 4(16 kg + 2m) + j]`, `j = 0..7` (2 float4), split `x = hi + lo` in fp16 (two WMMAs, error 1e-7).
`prep_b_tqw` does this once per call into 32 contiguous bytes per (block, m, kg, column).
* *States.* local step `u` is at chunk-relative bit `(15 - u) K`. Window 0 (u 0..7) = chunk bits `[8K, 16K)` + the low `15 - K` bits of the **partner lane's
chunk** (`lane ^ 16`, same row and block; circular wrap: for kg = 0 the partner is kg = 1) - one `__shfl_xor(x, 16)`; window 1 (u 8..15) = chunk bits `[0, 7K + 15)`.
`state(u) = (window >> offset) & 0x7fff`. Both windows fit 64 bits for K <= 7.
* *A fragment.* computed code `3single`: `w0 = ((s*89226354 + 64248484) & 0x8FFF8FFF) ^ 0x3B603B60`, `w1 = ((s*0x9E3779B1 + 0x7F4A7C15) & ...) ^ ...`;
the four half values of a step are `lo(w0), hi(w0), lo(w1), hi(w1)` = 2 words of the 8-half A vector. Table codebook: `x = s*0x9e3779b1`,
words `lut[x >> 21]`, `lut[(x >> 10) & 2047]` from an 8 KB LDS table of half2 (the table is exact in fp16: 0 inexact entries).
* *Accumulate.* D (8 floats) after the 8 (16 with lo) WMMAs of a block times the row scale (`fp16 d`, 8 rows per lane) is added to the running `tot[8]`; at the end lane
`(n = l % 16 < NB, kg)` stores rows `8 kg .. 8 kg + 7` of column `n`.
* Wave32 (the gfx12 default); 128-thread blocks (4 waves), `T = 2` tiles per wave first; VGPR budget: B fragments of one block half (8 m x 8 regs = 64), records `T K`,
windows, A (4), D (8) - fits well under 256.
4. **Compare with the emulator** on the same random streams; the CUDA harness (`tqk_lab.cu`) has the benchmark shape (12 gate/up + 6 down matrices) to copy.
Speed targets on gfx1201: K5/3single at 640 GB/s is a 3.7 Tw/s roof; WMMA hi+lo costs 2 x 8 WMMAs per 2048 weights per wave, the ALU side (2 IMAD + 2 LOP3 a step) is
light, so expect the memory system to be the limit - the opposite of the A4000, where the tensor pipe is at 75 percent.
5. Not decided here: whether the R9700 build should keep the table codebook (K6/K7 are byte-compatible with agentionai and must) or the computed code (K4/K5 new types) -
see notes-dsv41-cudalab.md.
+117
View File
@@ -0,0 +1,117 @@
// tools/dsv41_lab/hip/tqk_gemv_wmma.hip.cpp - gfx12 (RDNA4, R9700 = gfx1201) port of gemv_v3 / gemv_v3c. NOT COMPILED OR RUN on any
// machine yet: it is the line-by-line HIP form of tools/dsv41_lab/wmma_emu.hpp, whose host emulation matches the double reference
// (wmma_emu_test). Port steps: (1) run wmma_probe.hip.cpp; (2) hipcc this file with the test main you need; (3) compare against
// the emulator (same layout TQW, same inputs) lane by lane if anything differs.
// Differences to the CUDA path, all forced by the instruction: mma.m16n8k16 (A 16x16 as 4 regs, B 16x8 as 2 regs, D 4 floats) becomes
// v_wmma_f32_16x16x16_f16 (A 8 halves, B 8 halves, D 8 floats, 16 columns of which NB <= 5 are used); a lane holds ONE row of A
// and 8 rows of D (not two rows of A / D); the lane owns 16 consecutive steps of a block (not 8); hence layout TQW, not TQL.
#include <hip/hip_runtime.h>
#include <cstdint>
typedef _Float16 half8_t __attribute__((ext_vector_type(8)));
typedef float float8_t __attribute__((ext_vector_type(8)));
namespace tqw_hip {
constexpr uint32_t kMask = 0x7fffu;
struct Job {
const uint32_t* words; // TQW words [tile][P][K][32 lanes]
const uint16_t* scales; // [tile][P][16 rows][2 blocks] fp16
const half8_t* xb; // prepared B fragments (prep_b_tqw)
float* y; // [NB][ldy]
int rows, in, ldy;
};
// 3single computed code (computed_codes.hpp): a step's four weights are two LCG words, read as two half2 each. For the table
// codebook replace it by two lookups into an 8 KB LDS table of half2 (lut[x >> 21], lut[(x >> 10) & 2047], x = s * 0x9e3779b1).
__device__ __forceinline__ void step_words(uint32_t s, uint32_t& w0, uint32_t& w1) {
w0 = ((s * 89226354u + 64248484u) & 0x8FFF8FFFu) ^ 0x3B603B60u;
w1 = ((s * 0x9E3779B1u + 0x7F4A7C15u) & 0x8FFF8FFFu) ^ 0x3B603B60u;
}
__device__ __forceinline__ uint32_t funnel_r(uint32_t lo, uint32_t hi, int sh) { return (uint32_t) ((((uint64_t) hi << 32) | lo) >> sh); }
// activations -> B fragments. out[(((blk * 8 + m) * 2 + kg) * nb + n) * 2 + {0 = hi, 1 = lo}] = 8 halves of x[n][blk * 128 + 4 * (16 kg + 2 m) + j]
__global__ void prep_b_tqw(const float* x, int ldx, int nb, int in, half8_t* out) {
const int nblk = in / 128;
const size_t gid = (size_t) blockIdx.x * blockDim.x + threadIdx.x, n_all = (size_t) nblk * 8 * 2 * nb;
if (gid >= n_all) return;
const int n = (int) (gid % nb), kg = (int) ((gid / nb) % 2), m = (int) ((gid / (2 * nb)) % 8), blk = (int) (gid / (16 * nb));
const float* p = x + (size_t) n * ldx + blk * 128 + 4 * (16 * kg + 2 * m);
half8_t hi, lo;
for (int j = 0; j < 8; ++j) { hi[j] = (_Float16) p[j]; lo[j] = (_Float16) (p[j] - (float) hi[j]); }
out[gid * 2] = hi;
out[gid * 2 + 1] = lo;
}
// one wave = T tiles of 16 rows. K = bits per step (4..7), NB = columns (<= 16), T tiles per wave, EXACT: hi + lo activations.
template <int K, int NB, int T, int EXACT>
__global__ void __launch_bounds__(128) gemv(const Job* jobs) {
const Job job = jobs[blockIdx.y];
const int wave = threadIdx.x >> 5, lane = threadIdx.x & 31, r = lane & 15, kg = lane >> 4;
const int tile0 = (blockIdx.x * (blockDim.x >> 5) + wave) * T;
if (tile0 * 16 >= job.rows) return;
const int nblk = job.in / 128, NP = nblk / 2;
float tot[T][8];
for (int t = 0; t < T; ++t)
for (int i = 0; i < 8; ++i) tot[t][i] = 0.f;
for (int P = 0; P < NP; ++P) {
uint32_t rec[T][K];
for (int t = 0; t < T; ++t)
for (int j = 0; j < K; ++j) rec[t][j] = __builtin_nontemporal_load(job.words + (((size_t) (tile0 + t) * NP + P) * K + j) * 32 + lane);
for (int bk = 0; bk < 2; ++bk) {
half8_t bh[8], bl[8];
if (r < NB) {
for (int m = 0; m < 8; ++m) {
const half8_t* p = job.xb + (((((size_t) (2 * P + bk) * 8 + m) * 2 + kg) * NB + r) * 2);
bh[m] = p[0];
if (EXACT) bl[m] = p[1];
}
} else {
for (int m = 0; m < 8; ++m) { bh[m] = half8_t{0, 0, 0, 0, 0, 0, 0, 0}; bl[m] = bh[m]; }
}
for (int t = 0; t < T; ++t) {
// chunk bk of the record: bits [16 K bk, 16 K bk + 16 K); window 0 = steps u 0..7 (+ 15-K bits of the partner chunk),
// window 1 = steps u 8..15
const int b0 = 16 * K * bk;
auto bits = [&](int pos, int n) -> uint64_t { // n <= 56 bits at record bit pos, from the register words
const int a = pos >> 5, sh = pos & 31;
uint32_t w0 = rec[t][a], w1 = a + 1 < K ? rec[t][a + 1 < K ? a + 1 : 0] : 0u, w2 = a + 2 < K ? rec[t][a + 2 < K ? a + 2 : 0] : 0u;
const uint64_t v = ((uint64_t) funnel_r(w1, w2, sh) << 32) | funnel_r(w0, w1, sh);
return v & ((1ull << n) - 1ull);
};
// (the compiler folds the constant positions; a, sh are compile-time after unrolling bk and the loops below)
const uint64_t lo8 = bits(b0, 8 * K), hi8 = bits(b0 + 8 * K, 8 * K);
const uint32_t mine = (uint32_t) (lo8 & 0xffffffffu); // the bits the PARTNER needs: this lane's chunk bits [0, 15 - K)
const uint32_t pc = __shfl_xor((int) mine, 16);
const uint64_t win0 = hi8 | ((uint64_t) (pc & ((1u << (15 - K)) - 1u)) << (8 * K));
const uint64_t win1 = lo8 | ((hi8 & ((1ull << (15 - K)) - 1ull)) << (8 * K));
float8_t acc = {0, 0, 0, 0, 0, 0, 0, 0};
for (int m = 0; m < 8; ++m) {
half8_t a;
for (int s2 = 0; s2 < 2; ++s2) {
const int u = 2 * m + s2;
const uint32_t st = (uint32_t) (u < 8 ? win0 >> ((7 - u) * K) : win1 >> ((15 - u) * K)) & kMask;
uint32_t w0, w1;
step_words(st, w0, w1);
a[4 * s2 + 0] = __builtin_bit_cast(_Float16, (uint16_t) (w0 & 0xffffu));
a[4 * s2 + 1] = __builtin_bit_cast(_Float16, (uint16_t) (w0 >> 16));
a[4 * s2 + 2] = __builtin_bit_cast(_Float16, (uint16_t) (w1 & 0xffffu));
a[4 * s2 + 3] = __builtin_bit_cast(_Float16, (uint16_t) (w1 >> 16));
}
acc = __builtin_amdgcn_wmma_f32_16x16x16_f16_w32_gfx12(a, bh[m], acc);
if (EXACT) acc = __builtin_amdgcn_wmma_f32_16x16x16_f16_w32_gfx12(a, bl[m], acc);
}
// scales of rows 8 kg .. 8 kg + 7 of this block: 8 consecutive (row, bk) pairs of 2 -> stride 2
const uint16_t* sp = job.scales + (((size_t) (tile0 + t) * NP + P) * 16 + 8 * kg) * 2 + bk;
for (int i = 0; i < 8; ++i) tot[t][i] += (float) __builtin_bit_cast(_Float16, sp[2 * i]) * acc[i];
}
}
}
for (int t = 0; t < T; ++t)
if (r < NB)
for (int i = 0; i < 8; ++i) job.y[(size_t) r * job.ldy + (tile0 + t) * 16 + 8 * kg + i] = tot[t][i];
}
} // namespace tqw_hip
+40
View File
@@ -0,0 +1,40 @@
// tools/dsv41_lab/hip/wmma_probe.hip.cpp - run this FIRST on the gfx1201 box (one launch, no inputs): it checks the lane layout of
// __builtin_amdgcn_wmma_f32_16x16x16_f16_w32_gfx12 that wmma_emu.hpp and tqk_gemv_wmma.hip.cpp assume:
// A[m][k]: lane l holds a[j] = A[l % 16][8 * (l / 16) + j]; B[k][n]: lane l holds b[j] = B[8 * (l / 16) + j][l % 16]
// D[m][n]: lane l holds c[i] = D[8 * (l / 16) + i][l % 16]
// Probe 1: A[m][k] = m * 16 + k (exact in fp16), B = identity => D = A, so lane l's c[i] must be (8 (l/16) + i) * 16 + (l % 16).
// Probe 2: A = identity, B[k][n] = k * 16 + n => D = B, same expectation.
// A mismatch in probe 1 only means the A (or D) layout differs; in probe 2 only B (or D): the printout says which.
// hipcc --offload-arch=gfx1201 -O2 wmma_probe.hip.cpp -o wmma_probe && HIP_VISIBLE_DEVICES=<card> ./wmma_probe
#include <hip/hip_runtime.h>
#include <cstdio>
typedef _Float16 half8_t __attribute__((ext_vector_type(8)));
typedef float float8_t __attribute__((ext_vector_type(8)));
__global__ void probe(float* out, int which) {
const int l = threadIdx.x; // wave32
half8_t a, b;
for (int j = 0; j < 8; ++j) {
const int m = l % 16, k = 8 * (l / 16) + j; // the layout under test, for A
const int k2 = 8 * (l / 16) + j, n = l % 16; // for B
a[j] = (_Float16) (which == 0 ? (float) (m * 16 + k) : (m == k ? 1.f : 0.f));
b[j] = (_Float16) (which == 0 ? (k2 == n ? 1.f : 0.f) : (float) (k2 * 16 + n));
}
float8_t c = {0, 0, 0, 0, 0, 0, 0, 0};
c = __builtin_amdgcn_wmma_f32_16x16x16_f16_w32_gfx12(a, b, c);
for (int i = 0; i < 8; ++i) out[(which * 32 + l) * 8 + i] = c[i];
}
int main() {
float* d; hipMalloc(&d, 2 * 32 * 8 * sizeof(float));
probe<<<1, 32>>>(d, 0); probe<<<1, 32>>>(d, 1);
float h[2 * 32 * 8]; hipMemcpy(h, d, sizeof h, hipMemcpyDeviceToHost);
int bad[2] = {0, 0};
for (int w = 0; w < 2; ++w)
for (int l = 0; l < 32; ++l)
for (int i = 0; i < 8; ++i) bad[w] += h[(w * 32 + l) * 8 + i] != (float) ((8 * (l / 16) + i) * 16 + (l % 16));
std::printf("probe 1 (A layout, D layout): %d of 256 values wrong\nprobe 2 (B layout, D layout): %d of 256 wrong\n%s\n", bad[0], bad[1],
(bad[0] || bad[1]) ? "LAYOUT DIFFERS: fix wmma_emu.hpp first (the emulator is the specification), then the kernel" : "layout as assumed");
return bad[0] || bad[1];
}
+236
View File
@@ -0,0 +1,236 @@
// 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;
const uint64_t* sc; // v3 (TQL layout) only: the scales, see tqk_repack.hpp
int in = 0; // v3: weights per row (x is then the prepared B-fragment array, see prep_b)
};
// 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);
}
}
// ------------------------------------------------------------------------------------------------------------
// v2: tensor cores. The point table is exactly representable in fp16 (int16 table / 8192, |n| < 1024 or <= 11
// significant bits), so a trellis step's four weights are two half2 words straight out of an 8 KB u32 table: no
// conversion, and they are the A fragment of mma.m16n8k16 as they are. Thread (g = lane/4, q = lane%4) of a 16-row
// tile holds rows g and g+8; mma m of a 128-weight block takes step t = 8q + m of both rows (k slots 2q, 2q+1, 2q+8,
// 2q+9 = weights 4t..4t+3) against the activations x[col g][4t..4t+3] (B fragment, columns 0..NB-1 of the 8). The k
// order inside an mma is free as long as A and B agree. The activations are split x = hi + lo (two fp16) so the
// product is accurate to ~2^-22 relative (EXACT = 1; EXACT = 0 uses hi only, fp16-rounded activations). The block
// scale d is applied per row after the block's 8 (16) mma. D lands in rows g / g+8, columns 2q, 2q+1: stored directly.
__device__ __forceinline__ void mma16816(float* c, uint32_t a0, uint32_t a1, uint32_t a2, uint32_t a3, uint32_t b0, uint32_t b1) {
asm volatile("mma.sync.aligned.m16n8k16.row.col.f32.f16.f16.f32 {%0,%1,%2,%3}, {%4,%5,%6,%7}, {%8,%9}, {%0,%1,%2,%3};\n"
: "+f"(c[0]), "+f"(c[1]), "+f"(c[2]), "+f"(c[3])
: "r"(a0), "r"(a1), "r"(a2), "r"(a3), "r"(b0), "r"(b1));
}
__device__ __forceinline__ uint32_t h2bits(__half2 h) { return *(uint32_t*) &h; }
// the 4 states of steps 4l..4l+3 -> the 8 table entries needed: es[i][0..1]
template <int K, int NB, int T, int EXACT>
__global__ void __launch_bounds__(128) gemv_v2(const Job* __restrict__ jobs, const uint32_t* __restrict__ lut_g, int in) {
__shared__ uint32_t 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, g = lane >> 2, q = lane & 3;
const int row0 = (blockIdx.x * (blockDim.x >> 5) + warp) * 16 * T;
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 tot[T][4];
#pragma unroll
for (int t = 0; t < T; ++t)
#pragma unroll
for (int i = 0; i < 4; ++i) tot[t][i] = 0.f;
for (int b = 0; b < nblk; ++b) {
uint32_t bh[8][2], bl[8][2];
if (g < NB) {
const float4* xp = (const float4*) (job.x + (size_t) g * job.ldx + b * 128 + 32 * q);
#pragma unroll
for (int m = 0; m < 8; ++m) {
const float4 v = __ldg(xp + m);
const __half2 h0 = __floats2half2_rn(v.x, v.y), h1 = __floats2half2_rn(v.z, v.w);
bh[m][0] = h2bits(h0); bh[m][1] = h2bits(h1);
if (EXACT) {
bl[m][0] = h2bits(__floats2half2_rn(v.x - __low2float(h0), v.y - __high2float(h0)));
bl[m][1] = h2bits(__floats2half2_rn(v.z - __low2float(h1), v.w - __high2float(h1)));
}
}
} else {
#pragma unroll
for (int m = 0; m < 8; ++m) { bh[m][0] = bh[m][1] = bl[m][0] = bl[m][1] = 0u; }
}
#pragma unroll
for (int t = 0; t < T; ++t) {
uint32_t ea[2][8], eb[2][8]; // [row half][m]
float dd[2];
#pragma unroll
for (int h = 0; h < 2; ++h) {
const int row = row0 + t * 16 + g + 8 * h;
const uint8_t* blk = job.w + (size_t) row * row_bytes + (size_t) b * bsz;
dd[h] = __half2float(__ushort_as_half(*(const uint16_t*) blk));
#pragma unroll
for (int u = 0; u < 2; ++u) {
uint32_t s[4];
states4<K>((const uint16_t*) (blk + 2), 2 * q + u, s);
#pragma unroll
for (int i = 0; i < 4; ++i) {
const uint32_t x = s[i] * kHash;
ea[h][4 * u + i] = lut[x >> 21];
eb[h][4 * u + i] = lut[(x >> 10) & 2047u];
}
}
}
float acc[4] = {0.f, 0.f, 0.f, 0.f};
#pragma unroll
for (int m = 0; m < 8; ++m) {
mma16816(acc, ea[0][m], ea[1][m], eb[0][m], eb[1][m], bh[m][0], bh[m][1]);
if (EXACT) mma16816(acc, ea[0][m], ea[1][m], eb[0][m], eb[1][m], bl[m][0], bl[m][1]);
}
tot[t][0] += dd[0] * acc[0]; tot[t][1] += dd[0] * acc[1];
tot[t][2] += dd[1] * acc[2]; tot[t][3] += dd[1] * acc[3];
}
}
#pragma unroll
for (int t = 0; t < T; ++t)
#pragma unroll
for (int i = 0; i < 4; ++i) {
const int col = 2 * q + (i & 1), row = row0 + t * 16 + g + 8 * (i >> 1);
if (col < NB) job.y[(size_t) col * job.ldy + row] = tot[t][i];
}
}
} // namespace tqlab
+118
View File
@@ -0,0 +1,118 @@
// tools/dsv41_lab/tqk_gemv3.cuh - v3: tensor-core GEMV over the TQL layout (tqk_repack.hpp); include after tqk_gemv.cuh.
// Every lane's stream bits and the scales arrive in K + 1 fully coalesced loads per (16-row tile, block pair) - K words and one
// u64 shared by the quad - instead of ~18 u16 loads over 8 cache lines. The 15-bit states of a lane's 8 steps need 15 - K
// bits from lane q-1's chunk (circular): one shuffle per chunk.
#pragma once
#include "tqk_gemv.cuh"
namespace tqlab {
template <int K, int NB, int T, int EXACT>
__global__ void __launch_bounds__(128) gemv_v3(const Job* __restrict__ jobs, const uint32_t* __restrict__ lut_g, int in) {
__shared__ uint32_t 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, g = lane >> 2, q = lane & 3;
const int tile0 = (blockIdx.x * (blockDim.x >> 5) + warp) * T;
if (tile0 * 16 >= job.rows) return;
const int nblk = job.in / 128, NP = nblk / 2;
float tot[T][4];
#pragma unroll
for (int t = 0; t < T; ++t)
#pragma unroll
for (int i = 0; i < 4; ++i) tot[t][i] = 0.f;
const int src_lane = 4 * g + ((q + 3) & 3);
for (int P = 0; P < NP; ++P) {
uint32_t bh[2][8][2], bl[2][8][2];
#pragma unroll
for (int bk = 0; bk < 2; ++bk) {
if (g < NB) {
const uint4* xp = ((const uint4*) job.x) + (((size_t) (2 * P + bk) * 8) * NB + g) * 4 + q;
#pragma unroll
for (int m = 0; m < 8; ++m) {
const uint4 v = __ldg(xp + (size_t) m * NB * 4);
bh[bk][m][0] = v.x;
bh[bk][m][1] = v.y;
if (EXACT) { bl[bk][m][0] = v.z; bl[bk][m][1] = v.w; }
}
} else {
#pragma unroll
for (int m = 0; m < 8; ++m) { bh[bk][m][0] = bh[bk][m][1] = bl[bk][m][0] = bl[bk][m][1] = 0u; }
}
}
#pragma unroll
for (int t = 0; t < T; ++t) {
const size_t base = (size_t) (tile0 + t) * NP + P;
uint32_t r[K];
#pragma unroll
for (int j = 0; j < K; ++j) r[j] = __ldcs(((const uint32_t*) job.w) + (base * K + j) * 32 + lane);
const uint64_t dq = __ldcs(job.sc + base * 8 + g);
// windows of the 4 chunks: own 8K bits + the low 15-K bits of lane q-1's chunk
uint64_t win[4];
#pragma unroll
for (int i = 0; i < 4; ++i) {
const int a = (8 * K * i) >> 5, sh = (8 * K * i) & 31;
const uint32_t w0 = r[a];
const uint32_t w1 = a + 1 < K ? r[a + 1 < K ? a + 1 : 0] : 0u;
const uint32_t w2 = a + 2 < K ? r[a + 2 < K ? a + 2 : 0] : 0u;
const uint32_t lo = __funnelshift_r(w0, w1, sh), hi = __funnelshift_r(w1, w2, sh);
const uint64_t ch = (((uint64_t) hi << 32) | lo) & ((1ull << (8 * K)) - 1ull);
const uint32_t fw = __shfl_sync(0xffffffffu, lo, src_lane);
win[i] = ch | ((uint64_t) (fw & ((1u << (15 - K)) - 1u)) << (8 * K));
}
uint32_t ea[2][2][8], eb[2][2][8]; // [bk][h][m]
#pragma unroll
for (int i = 0; i < 4; ++i)
#pragma unroll
for (int m = 0; m < 8; ++m) {
const uint32_t s = (uint32_t) (win[i] >> ((7 - m) * K)) & kMask;
const uint32_t x = s * kHash;
ea[i >> 1][i & 1][m] = lut[x >> 21];
eb[i >> 1][i & 1][m] = lut[(x >> 10) & 2047u];
}
#pragma unroll
for (int bk = 0; bk < 2; ++bk) {
float acc[4] = {0.f, 0.f, 0.f, 0.f};
#pragma unroll
for (int m = 0; m < 8; ++m) {
mma16816(acc, ea[bk][0][m], ea[bk][1][m], eb[bk][0][m], eb[bk][1][m], bh[bk][m][0], bh[bk][m][1]);
if (EXACT) mma16816(acc, ea[bk][0][m], ea[bk][1][m], eb[bk][0][m], eb[bk][1][m], bl[bk][m][0], bl[bk][m][1]);
}
const float d0 = __half2float(__ushort_as_half((unsigned short) (dq >> (16 * (2 * bk + 0)))));
const float d1 = __half2float(__ushort_as_half((unsigned short) (dq >> (16 * (2 * bk + 1)))));
tot[t][0] += d0 * acc[0];
tot[t][1] += d0 * acc[1];
tot[t][2] += d1 * acc[2];
tot[t][3] += d1 * acc[3];
}
}
}
#pragma unroll
for (int t = 0; t < T; ++t)
#pragma unroll
for (int i = 0; i < 4; ++i) {
const int col = 2 * q + (i & 1), row = (tile0 + t) * 16 + g + 8 * (i >> 1);
if (col < NB) job.y[(size_t) col * job.ldy + row] = tot[t][i];
}
}
} // namespace tqlab
namespace tqlab {
// activations -> B fragments, once per call: out[(((blk * 8 + m) * nb + c) * 4 + q)] = {hi(x0,x1), hi(x2,x3), lo(x0,x1), lo(x2,x3)}
// for x[c][blk * 128 + 32 q + 4 m .. +3] (hi = fp16(x), lo = fp16(x - hi): hi + lo is x to ~2^-22).
__global__ void prep_b(const float* __restrict__ x, int ldx, int nb, int in, uint4* __restrict__ out) {
const int nblk = in / 128;
const size_t gid = (size_t) blockIdx.x * blockDim.x + threadIdx.x, n = (size_t) nb * nblk * 32;
if (gid >= n) return;
const int m = gid & 7, q = (gid >> 3) & 3;
const size_t cb = gid >> 5; // c * nblk + blk
const int c = (int) (cb / nblk), blk = (int) (cb % nblk);
const float4 v = *(const float4*) (x + (size_t) c * ldx + blk * 128 + 32 * q + 4 * m);
const __half2 h0 = __floats2half2_rn(v.x, v.y), h1 = __floats2half2_rn(v.z, v.w);
out[(((size_t) blk * 8 + m) * nb + c) * 4 + q] = make_uint4(h2bits(h0), h2bits(h1), h2bits(__floats2half2_rn(v.x - __low2float(h0), v.y - __high2float(h0))),
h2bits(__floats2half2_rn(v.z - __low2float(h1), v.w - __high2float(h1))));
}
} // namespace tqlab
+109
View File
@@ -0,0 +1,109 @@
// tools/dsv41_lab/tqk_gemv_c.cuh - v3 with a COMPUTED codebook instead of the 2048-entry table (LUT-free): the step's four weights
// come from 2 or 4 LCG words, x_i = s * A_i + B_i, w = (x_i & 0x8FFF8FFF) ^ 0x3B603B60 read as two fp16 (QTIP 3INST's trick;
// computed_codes.hpp). CODE 0 "3single": the two words are the A fragment (a0, a2) as they are: 2 IMAD + 2 LOP3 a step.
// CODE 1 "3sum": a0 = HADD2(w0, w1), a2 = HADD2(w2, w3): 4 IMAD + 4 LOP3 + 2 HADD2. No shared-memory table, no __syncthreads.
// Everything else (TQL layout, prepared B fragments, mma) is gemv_v3.
#pragma once
#include "tqk_gemv3.cuh"
namespace tqlab {
__device__ __forceinline__ uint32_t cword(uint32_t s, int i) {
constexpr uint32_t A[4] = {89226354u, 0x9E3779B1u, 0x85EBCA6Bu, 0xC2B2AE35u};
constexpr uint32_t B[4] = {64248484u, 0x7F4A7C15u, 0x165667B1u, 0x27D4EB2Fu};
return ((s * A[i] + B[i]) & 0x8FFF8FFFu) ^ 0x3B603B60u;
}
__device__ __forceinline__ uint32_t hadd2_u(uint32_t a, uint32_t b) {
__half2 x = *(__half2*) &a, y = *(__half2*) &b;
const __half2 r = __hadd2(x, y);
return *(const uint32_t*) &r;
}
template <int K, int NB, int T, int EXACT, int CODE>
__global__ void __launch_bounds__(128) gemv_v3c(const Job* __restrict__ jobs, const uint32_t* __restrict__ lut_unused, int in_unused) {
const Job job = jobs[blockIdx.y];
const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31, g = lane >> 2, q = lane & 3;
const int tile0 = (blockIdx.x * (blockDim.x >> 5) + warp) * T;
if (tile0 * 16 >= job.rows) return;
const int nblk = job.in / 128, NP = nblk / 2;
float tot[T][4];
#pragma unroll
for (int t = 0; t < T; ++t)
#pragma unroll
for (int i = 0; i < 4; ++i) tot[t][i] = 0.f;
const int src_lane = 4 * g + ((q + 3) & 3);
for (int P = 0; P < NP; ++P) {
uint32_t bh[2][8][2], bl[2][8][2];
#pragma unroll
for (int bk = 0; bk < 2; ++bk) {
if (g < NB) {
const uint4* xp = ((const uint4*) job.x) + (((size_t) (2 * P + bk) * 8) * NB + g) * 4 + q;
#pragma unroll
for (int m = 0; m < 8; ++m) {
const uint4 v = __ldg(xp + (size_t) m * NB * 4);
bh[bk][m][0] = v.x;
bh[bk][m][1] = v.y;
if (EXACT) { bl[bk][m][0] = v.z; bl[bk][m][1] = v.w; }
}
} else {
#pragma unroll
for (int m = 0; m < 8; ++m) { bh[bk][m][0] = bh[bk][m][1] = bl[bk][m][0] = bl[bk][m][1] = 0u; }
}
}
#pragma unroll
for (int t = 0; t < T; ++t) {
const size_t base = (size_t) (tile0 + t) * NP + P;
uint32_t r[K];
#pragma unroll
for (int j = 0; j < K; ++j) r[j] = __ldcs(((const uint32_t*) job.w) + (base * K + j) * 32 + lane);
const uint64_t dq = __ldcs(job.sc + base * 8 + g);
uint64_t win[4];
#pragma unroll
for (int i = 0; i < 4; ++i) {
const int a = (8 * K * i) >> 5, sh = (8 * K * i) & 31;
const uint32_t w0 = r[a];
const uint32_t w1 = a + 1 < K ? r[a + 1 < K ? a + 1 : 0] : 0u;
const uint32_t w2 = a + 2 < K ? r[a + 2 < K ? a + 2 : 0] : 0u;
const uint32_t lo = __funnelshift_r(w0, w1, sh), hi = __funnelshift_r(w1, w2, sh);
const uint64_t ch = (((uint64_t) hi << 32) | lo) & ((1ull << (8 * K)) - 1ull);
const uint32_t fw = __shfl_sync(0xffffffffu, lo, src_lane);
win[i] = ch | ((uint64_t) (fw & ((1u << (15 - K)) - 1u)) << (8 * K));
}
#pragma unroll
for (int bk = 0; bk < 2; ++bk) {
float acc[4] = {0.f, 0.f, 0.f, 0.f};
#pragma unroll
for (int m = 0; m < 8; ++m) {
uint32_t a0, a1, a2, a3; // (row g, slots 2q..), (row g+8, ..), (row g, slots 2q+8..), (row g+8, ..)
{
const uint32_t s = (uint32_t) (win[2 * bk + 0] >> ((7 - m) * K)) & kMask;
if (CODE == 0) { a0 = cword(s, 0); a2 = cword(s, 1); }
else { a0 = hadd2_u(cword(s, 0), cword(s, 1)); a2 = hadd2_u(cword(s, 2), cword(s, 3)); }
}
{
const uint32_t s = (uint32_t) (win[2 * bk + 1] >> ((7 - m) * K)) & kMask;
if (CODE == 0) { a1 = cword(s, 0); a3 = cword(s, 1); }
else { a1 = hadd2_u(cword(s, 0), cword(s, 1)); a3 = hadd2_u(cword(s, 2), cword(s, 3)); }
}
mma16816(acc, a0, a1, a2, a3, bh[bk][m][0], bh[bk][m][1]);
if (EXACT) mma16816(acc, a0, a1, a2, a3, bl[bk][m][0], bl[bk][m][1]);
}
const float d0 = __half2float(__ushort_as_half((unsigned short) (dq >> (16 * (2 * bk + 0)))));
const float d1 = __half2float(__ushort_as_half((unsigned short) (dq >> (16 * (2 * bk + 1)))));
tot[t][0] += d0 * acc[0];
tot[t][1] += d0 * acc[1];
tot[t][2] += d1 * acc[2];
tot[t][3] += d1 * acc[3];
}
}
}
#pragma unroll
for (int t = 0; t < T; ++t)
#pragma unroll
for (int i = 0; i < 4; ++i) {
const int col = 2 * q + (i & 1), row = (tile0 + t) * 16 + g + 8 * (i >> 1);
if (col < NB) job.y[(size_t) col * job.ldy + row] = tot[t][i];
}
}
} // namespace tqlab
+294
View File
@@ -0,0 +1,294 @@
// 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 "tqk_gemv3.cuh"
#include "tqk_gemv_c.cuh"
#include "tqk_repack.hpp"
#include "../trellis/tqenc.hpp"
#include "strata/kernels/cpu/tq_cpu.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;
}
struct KFn { const void* f; int threads; int rows_per_cta; int lutkind; int tql = 0; }; // lutkind 0: float2 table, 1: u32 half2 table
template <int K, int NB> static KFn pick(int variant) {
switch (variant) {
case 1: return {(const void*) gemv_v1<K, NB, 1>, 256, 8, 0};
case 2: return {(const void*) gemv_v1<K, NB, 2>, 256, 16, 0};
case 3: return {(const void*) gemv_v2<K, NB, 1, 1>, 128, 64, 1};
case 4: return {(const void*) gemv_v2<K, NB, 2, 1>, 128, 128, 1};
case 5: return {(const void*) gemv_v2<K, NB, 4, 1>, 128, 256, 1};
case 6: return {(const void*) gemv_v2<K, NB, 2, 0>, 128, 128, 1};
case 7: return {(const void*) gemv_v2<K, NB, 4, 0>, 128, 256, 1};
case 8: return {(const void*) gemv_v3<K, NB, 1, 1>, 128, 64, 1, 1};
case 9: return {(const void*) gemv_v3<K, NB, 2, 1>, 128, 128, 1, 1};
case 10: return {(const void*) gemv_v3<K, NB, 4, 1>, 128, 256, 1, 1};
case 11: return {(const void*) gemv_v3<K, NB, 2, 0>, 128, 128, 1, 1};
case 12: return {(const void*) gemv_v3c<K, NB, 4, 1, 0>, 128, 256, 1, 1};
case 13: return {(const void*) gemv_v3c<K, NB, 4, 1, 1>, 128, 256, 1, 1};
case 14: return {(const void*) gemv_v3c<K, NB, 2, 1, 0>, 128, 128, 1, 1};
case 15: return {(const void*) gemv_v3c<K, NB, 2, 1, 1>, 128, 128, 1, 1};
case 16: return {(const void*) gemv_v3c<K, NB, 2, 0, 0>, 128, 128, 1, 1};
case 17: return {(const void*) gemv_v3c<K, NB, 4, 0, 0>, 128, 256, 1, 1};
default: return {(const void*) gemv_v3c<K, NB, 1, 0, 0>, 128, 64, 1, 1};
}
}
template <int K> static KFn 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 KFn 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 const float2* g_lut_f2; static const uint32_t* g_lut_u32;
static void launch(const KFn& k, const Job* jd, int njobs, int rows, int in, cudaStream_t s = 0) {
dim3 grid((rows + k.rows_per_cta - 1) / k.rows_per_cta, njobs);
const void* lut = k.lutkind ? (const void*) g_lut_u32 : (const void*) g_lut_f2;
void* args[] = {(void*) &jd, (void*) &lut, (void*) &in};
cudaLaunchKernel(k.f, grid, dim3(k.threads), args, 0, s);
}
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));
g_lut_f2 = lut;
{ // half2 table: must be exact (the claim the tensor-core kernels rest on)
std::vector<uint32_t> hl(2048); int inexact = 0;
for (int i = 0; i < 2048; ++i) {
const uint16_t a = tqenc::float_to_half(pt[2 * i]), b = tqenc::float_to_half(pt[2 * i + 1]);
inexact += tqenc::half_to_float(a) != pt[2 * i] || tqenc::half_to_float(b) != pt[2 * i + 1];
hl[i] = a | ((uint32_t) b << 16);
}
std::printf("fp16 point table inexact entries: %d\n", inexact);
uint32_t* d; CK(cudaMalloc(&d, 8192)); CK(cudaMemcpy(d, hl.data(), 8192, cudaMemcpyHostToDevice)); g_lut_u32 = d;
}
// 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) && !std::getenv("TQE_CODE"); // (the table kernel is meaningless under a computed code)
// ---- parity 2: GEMV vs double reference on the decoded weights, rows x in small
for (int nb : NBs) {
const int rows = 256, in = 768, 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());
uint8_t* mwd; CK(cudaMalloc(&mwd, mw.size())); CK(cudaMemcpy(mwd, mw.data(), mw.size(), cudaMemcpyHostToDevice));
const KFn kf = pick_k(K, nb, variant); const uint64_t* scd = nullptr; uint8_t* wd = mwd;
if (kf.tql) { std::vector<uint32_t> words; std::vector<uint64_t> sc; repack_tql(K, mw.data(), rows, nblk, words, sc);
CK(cudaMalloc(&wd, words.size() * 4)); CK(cudaMemcpy(wd, words.data(), words.size() * 4, cudaMemcpyHostToDevice));
uint64_t* t; CK(cudaMalloc(&t, sc.size() * 8)); CK(cudaMemcpy(t, sc.data(), sc.size() * 8, cudaMemcpyHostToDevice)); scd = t; }
auto gpu_run = [&](const std::vector<float>& x) {
float* xd = dev_f32(x); float* yd; CK(cudaMalloc(&yd, (size_t) nb * rows * 4));
float* xj = xd;
if (kf.tql) { const size_t n = (size_t) nb * (in / 128) * 32; uint4* xb; CK(cudaMalloc(&xb, n * 16)); prep_b<<<(int) ((n + 255) / 256), 256>>>(xd, in, nb, in, xb); CK(cudaDeviceSynchronize()); xj = (float*) xb; }
Job j{wd, xj, yd, rows, in, rows, scd, in}; Job* jd; CK(cudaMalloc(&jd, sizeof(Job))); CK(cudaMemcpy(jd, &j, sizeof(Job), cudaMemcpyHostToDevice));
launch(kf, jd, 1, rows, in); CK(cudaGetLastError());
std::vector<float> y((size_t) nb * rows); CK(cudaMemcpy(y.data(), yd, y.size() * 4, cudaMemcpyDeviceToHost));
cudaFree(xd); cudaFree(yd); cudaFree(jd); if (kf.tql) cudaFree(xj);
return y;
};
// (1) random F32 activations vs a double reference on the decoded weights
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; }
std::vector<float> y = gpu_run(x);
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 || (variant >= 16 && variant <= 18 && worst < 1e-4);
// (2) the CPU kernel of the repo (tq_cpu scalar and AVX2, Q8_0 activations): same weights; the GPU runs on the dequantised Q8_0 activations
std::vector<uint8_t> q8((size_t) nb * (in / 32) * 34); std::vector<float> xq((size_t) nb * in);
for (int c = 0; c < nb; ++c) for (int b = 0; b < in / 32; ++b) {
float amax = 0; for (int i = 0; i < 32; ++i) amax = std::max(amax, std::fabs(x[(size_t) c * in + b * 32 + i]));
const uint16_t dh = tqenc::float_to_half(amax / 127.f); const float df = amax / 127.f, id = df ? 1.f / df : 0.f, dr = tqenc::half_to_float(dh);
uint8_t* blk = &q8[((size_t) c * (in / 32) + b) * 34]; std::memcpy(blk, &dh, 2);
for (int i = 0; i < 32; ++i) { const int qv = (int) std::lround(x[(size_t) c * in + b * 32 + i] * id); blk[2 + i] = (uint8_t) (int8_t) qv; xq[(size_t) c * in + b * 32 + i] = qv * dr; }
}
std::vector<float> ycpu_s((size_t) nb * rows), ycpu_a((size_t) nb * rows);
const bool have_avx2 = strata::kernels::cpu::tq_isa_ok(strata::kernels::cpu::TqIsa::avx2);
{ const void* act[8]; float* os[8]; float* oa[8];
for (int c = 0; c < nb; ++c) { act[c] = &q8[(size_t) c * (in / 32) * 34]; os[c] = &ycpu_s[(size_t) c * rows]; oa[c] = &ycpu_a[(size_t) c * rows]; }
const size_t row_bytes = (size_t) nblk * bsz;
strata::kernels::cpu::tq_rows(strata::kernels::cpu::TqIsa::scalar, type, mw.data(), row_bytes, in, act, nb, os, 0, rows);
if (have_avx2) strata::kernels::cpu::tq_rows(strata::kernels::cpu::TqIsa::avx2, type, mw.data(), row_bytes, in, act, nb, oa, 0, rows); }
std::vector<float> yq = gpu_run(xq);
std::vector<double> refq((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] * xq[(size_t) c * in + i]; s += t; sa += std::fabs(t); } refq[(size_t) c * rows + r] = s; refabs[(size_t) c * rows + r] = sa; }
double w_gc = 0, w_cr = 0, w_ac = 0;
for (size_t i = 0; i < yq.size(); ++i) { const double den = refabs[i] + 1e-30; w_gc = std::max(w_gc, std::fabs(yq[i] - ycpu_s[i]) / den); w_cr = std::max(w_cr, std::fabs(ycpu_s[i] - refq[i]) / den); if (have_avx2) w_ac = std::max(w_ac, std::fabs(ycpu_a[i] - ycpu_s[i]) / den); }
std::printf("gemv nb=%d: GPU vs double ref %.2e %s | vs CPU kernel of the repo (Q8_0 acts): GPU-CPU %.2e, CPU-double %.2e, avx2-scalar %.2e (all / sum|w x|)\n", nb, worst, ok ? "ok" : "FAIL", w_gc, w_cr, w_ac);
fails += !ok || (w_gc > 5e-6 && !std::getenv("TQE_CODE"));
cudaFree(mwd); if (kf.tql) { cudaFree(wd); }
}
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, (const uint64_t*) (p + (size_t) rows_gu * (in_gu / 128) * 4 * K)});
}
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, (const uint64_t*) (p + (size_t) rows_dn * (in_dn / 128) * 4 * K)});
}
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) {
KFn f = pick_k(K, nb, variant);
cudaEvent_t e0, e1; cudaEventCreate(&e0); cudaEventCreate(&e1);
Job* jall = nullptr; uint4* xb_gu = nullptr; uint4* xb_dn = nullptr;
if (f.tql) { // one launch for all 18 matrices; activations prepared once (prep_b)
const size_t gu_n = (size_t) nb * (in_gu / 128) * 32, dn_n = (size_t) nb * (in_dn / 128) * 32;
CK(cudaMalloc(&xb_gu, gu_n * 16)); CK(cudaMalloc(&xb_dn, dn_n * 16 * E));
prep_b<<<(int) ((gu_n + 255) / 256), 256>>>(xg_d, in_gu, nb, in_gu, xb_gu);
for (int e = 0; e < E; ++e) prep_b<<<(int) ((dn_n + 255) / 256), 256>>>(xdn_d + (size_t) e * maxnb * in_dn, in_dn, nb, in_dn, xb_dn + e * dn_n);
std::vector<Job> all = hj_gu; all.insert(all.end(), hj_dn.begin(), hj_dn.end());
for (size_t i = 0; i < all.size(); ++i) { const bool gu = i < hj_gu.size(); all[i].in = gu ? in_gu : in_dn; all[i].x = (const float*) (gu ? xb_gu : xb_dn + (i - hj_gu.size()) * dn_n); }
CK(cudaMalloc(&jall, sizeof(Job) * all.size())); CK(cudaMemcpy(jall, all.data(), sizeof(Job) * all.size(), cudaMemcpyHostToDevice));
CK(cudaDeviceSynchronize());
}
auto one = [&]() { if (f.tql) launch(f, jall, 3 * E, rows_dn, 0); else { launch(f, jgu, 2 * E, rows_gu, in_gu); launch(f, jdn, E, rows_dn, in_dn); } };
for (int w = 0; w < 5; ++w) one();
CK(cudaDeviceSynchronize()); cudaEventRecord(e0);
for (int r = 0; r < reps; ++r) one();
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);
if (jall) { cudaFree(jall); cudaFree(xb_gu); cudaFree(xb_dn); }
}
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;
}
// tq_cpu.cpp needs these probes from expert_layout.cpp: answer from the CPU itself
namespace strata::kernels::cpu {
bool cpu_avx2_ok() { return __builtin_cpu_supports("avx2") && __builtin_cpu_supports("fma") && __builtin_cpu_supports("f16c"); }
bool cpu_avx512_ok() { return false; }
}
+50
View File
@@ -0,0 +1,50 @@
// tools/dsv41_lab/tqk_repack.hpp - host reference of the "TQL" kernel layout of a trellis matrix (lossless bit permutation of
// the file layout; rows % 16 == 0, blocks per row even). See tqk_gemv3.cuh for why.
//
// A tile = 16 rows, a pair P = blocks 2P, 2P+1. Lane (g = lane/4, q = lane%4) of the mma tile owns, of each of the 4
// (block bk, row g + 8 h) stream chunks, the 8K bits at stream bit (24 - 8q) K (steps 8q .. 8q+7 of the block), chunk
// i = 2 bk + h. Its 4 chunks are 32 K bits = K words: words[((tile * NP + P) * K + j) * 32 + lane]. The scales:
// sc[(tile * NP + P) * 8 + g] = 4 x u16, slot 2 bk + h = fp16 d of (row g + 8 h, block 2P + bk).
#pragma once
#include <cstdint>
#include <cstring>
#include <vector>
namespace tqlab {
// file layout -> TQL: words (K * 32 per tile-pair) and scales (8 u64 per tile-pair)
inline void repack_tql(int K, const uint8_t* w, int rows, int nblk, std::vector<uint32_t>& words, std::vector<uint64_t>& sc) {
const int bsz = 2 + 4 * K, NP = nblk / 2, NT = rows / 16;
words.assign((size_t) NT * NP * K * 32, 0u);
sc.assign((size_t) NT * NP * 8, 0ull);
for (int t = 0; t < NT; ++t)
for (int P = 0; P < NP; ++P) {
const size_t base = (size_t) t * NP + P;
for (int g = 0; g < 8; ++g) {
uint64_t dq = 0;
for (int c = 0; c < 4; ++c) {
const int bk = c >> 1, h = c & 1;
const uint8_t* blk = w + ((size_t) (t * 16 + g + 8 * h) * nblk + 2 * P + bk) * bsz;
uint16_t d;
std::memcpy(&d, blk, 2);
dq |= (uint64_t) d << (16 * c);
}
sc[base * 8 + g] = dq;
for (int q = 0; q < 4; ++q) {
const int lane = 4 * g + q;
for (int i = 0; i < 4; ++i) {
const int bk = i >> 1, h = i & 1;
const uint8_t* blk = w + ((size_t) (t * 16 + g + 8 * h) * nblk + 2 * P + bk) * bsz;
for (int b = 0; b < 8 * K; ++b) { // chunk bit b -> record bit 8 K i + b
const int src = (24 - 8 * q) * K + b;
const uint32_t bit = (blk[2 + (src >> 3)] >> (src & 7)) & 1u;
const int dst = 8 * K * i + b;
words[(base * K + (dst >> 5)) * 32 + lane] |= bit << (dst & 31);
}
}
}
}
}
}
} // namespace tqlab
+168
View File
@@ -0,0 +1,168 @@
// tools/dsv41_lab/wmma_emu.hpp - host emulation of the gfx12 (RDNA4, R9700 = gfx1201) port of gemv_v3, written lane by lane exactly
// as the HIP kernel in hip/tqk_gemv_wmma.hip.cpp does it, so the data flow (layout "TQW", step -> k-slot map, window bits, shuffles, B
// fragments, D scaling) is checked on any machine against the double reference BEFORE it runs on the card. The only assumption
// that needs the card is the lane layout of v_wmma_f32_16x16x16_f16 (hip/wmma_probe.hip.cpp checks it in one launch).
//
// Assumed layout, wave32, __builtin_amdgcn_wmma_f32_16x16x16_f16_w32_gfx12(v8h a, v8h b, v8f c):
// A[m][k]: lane l holds a[j] = A[m = l % 16][k = 8 * (l / 16) + j], j = 0..7 (no replication between the lane halves)
// B[k][n]: lane l holds b[j] = B[k = 8 * (l / 16) + j][n = l % 16]
// D[m][n]: lane l holds c[i] = D[m = 8 * (l / 16) + i][n = l % 16], i = 0..7
#pragma once
#include "computed_codes.hpp"
#include <cstdint>
#include <cstring>
#include <vector>
namespace tqw {
struct Half8 { uint16_t h[8]; };
struct Float8 { float f[8]; };
// D = A * B + C on 32 lanes
inline void wmma_f32_16x16x16_f16(const Half8 a[32], const Half8 b[32], Float8 c[32]) {
float A[16][16], B[16][16], D[16][16];
for (int l = 0; l < 32; ++l)
for (int j = 0; j < 8; ++j) {
A[l % 16][8 * (l / 16) + j] = tqcode::h2f(a[l].h[j]);
B[8 * (l / 16) + j][l % 16] = tqcode::h2f(b[l].h[j]);
}
for (int l = 0; l < 32; ++l)
for (int i = 0; i < 8; ++i) D[8 * (l / 16) + i][l % 16] = c[l].f[i];
for (int m = 0; m < 16; ++m)
for (int n = 0; n < 16; ++n) {
double s = D[m][n];
for (int k = 0; k < 16; ++k) s += (double) A[m][k] * B[k][n];
D[m][n] = (float) s;
}
for (int l = 0; l < 32; ++l)
for (int i = 0; i < 8; ++i) c[l].f[i] = D[8 * (l / 16) + i][l % 16];
}
// ---- layout TQW (gfx12): a tile = 16 rows, a pair P = blocks 2P, 2P+1. Lane l = r + 16 kg of the wave owns row r and, of every
// block, the 16 steps u = 0..15 of the half kg (steps t = 16 kg + u): stream bits [(16 - 16 kg) K, (32 - 16 kg) K) of the block.
// Its two chunks (bk = 0, 1) are 32 K bits = K words: words[((tile * NP + P) * K + j) * 32 + lane].
// Scales: sc[((tile * NP + P) * 16 + r) * 2 + bk] (u16 fp16 d of row r, block 2P + bk): a lane reads the 8 rows 8 kg .. 8 kg + 7 = 32 bytes.
inline void repack_tqw(int K, const uint8_t* w, int rows, int nblk, std::vector<uint32_t>& words, std::vector<uint16_t>& sc) {
const int bsz = 2 + 4 * K, NP = nblk / 2, NT = rows / 16;
words.assign((size_t) NT * NP * K * 32, 0u);
sc.assign((size_t) NT * NP * 32, 0);
for (int t = 0; t < NT; ++t)
for (int P = 0; P < NP; ++P) {
const size_t base = (size_t) t * NP + P;
for (int r = 0; r < 16; ++r)
for (int bk = 0; bk < 2; ++bk) {
const uint8_t* blk = w + ((size_t) (t * 16 + r) * nblk + 2 * P + bk) * bsz;
std::memcpy(&sc[(base * 16 + r) * 2 + bk], blk, 2);
for (int kg = 0; kg < 2; ++kg) {
const int lane = r + 16 * kg;
for (int b = 0; b < 16 * K; ++b) { // chunk bit b -> record bit 16 K bk + b
const int src = (16 - 16 * kg) * K + b;
const uint32_t bit = (blk[2 + (src >> 3)] >> (src & 7)) & 1u;
const int dst = 16 * K * bk + b;
words[(base * K + (dst >> 5)) * 32 + lane] |= bit << (dst & 31);
}
}
}
}
}
// B fragments (prep_b of the CUDA path, gfx12 form): for column n < nb, block blk, mma m, k-group kg: 8 halves hi and 8 halves lo of
// x[n][blk * 128 + 4 * (16 kg + 2 m) + j], j = 0..7 (hi = fp16(x), lo = fp16(x - hi))
inline uint16_t f2h_rn(float f) { // fp16 round to nearest even (host)
uint32_t u; std::memcpy(&u, &f, 4);
const uint32_t s = (u >> 16) & 0x8000u; int e = (int) ((u >> 23) & 0xff) - 127 + 15; uint32_t m = u & 0x7fffffu;
if (((u >> 23) & 0xff) == 0xff) return (uint16_t) (s | 0x7c00u | (m ? 0x200u : 0));
if (e >= 31) return (uint16_t) (s | 0x7c00u);
if (e <= 0) {
if (e < -10) return (uint16_t) s;
m |= 0x800000u; const int sh = 14 - e; uint32_t hm = m >> sh; const uint32_t rem = m & ((1u << sh) - 1), half = 1u << (sh - 1);
if (rem > half || (rem == half && (hm & 1))) ++hm;
return (uint16_t) (s | hm);
}
uint32_t hm = m >> 13; const uint32_t rem = m & 0x1fffu;
uint32_t v = ((uint32_t) e << 10) | hm;
if (rem > 0x1000u || (rem == 0x1000u && (v & 1))) ++v;
return (uint16_t) (s | v);
}
// the A fragment of a lane for one trellis step: (word 0, word 1) -> 4 fp16 (weights 4t .. 4t+3). computed code "3single":
// the two LCG words as they are. table: the two half2 entries of the hash.
using StepFn = void (*)(uint32_t state, uint32_t out[2]);
// The kernel, wave by wave. x: nb columns of F32 activations [nb][in]. Returns y[nb][rows].
inline void gemv_tqw(int K, int nb, int rows, int in, const std::vector<uint32_t>& words, const std::vector<uint16_t>& sc,
const std::vector<float>& x, StepFn step, std::vector<float>& y, bool exact = true) {
const int nblk = in / 128, NP = nblk / 2, NT = rows / 16;
y.assign((size_t) nb * rows, 0.f);
for (int t = 0; t < NT; ++t) {
float tot[32][8] = {};
for (int P = 0; P < NP; ++P) {
const size_t base = (size_t) t * NP + P;
// per lane: the record, the two chunk windows (8 steps each) with the partner bits
uint64_t win[32][2][2]; // [lane][bk][half of the chunk: 0 = steps u 0..7, 1 = u 8..15]
for (int lane = 0; lane < 32; ++lane) {
uint32_t r[8];
for (int j = 0; j < K; ++j) r[j] = words[(base * K + j) * 32 + lane];
for (int bk = 0; bk < 2; ++bk) {
// chunk = record bits [16 K bk, 16 K (bk + 1)), up to 80 bits: read as two 64-bit pieces
auto bits = [&](int pos, int n) { // n <= 64 bits at record bit pos
uint64_t v = 0;
for (int i = 0; i < n; ++i) { const int p = pos + i; v |= (uint64_t) ((r[p >> 5] >> (p & 31)) & 1u) << i; }
return v;
};
const uint64_t lo8 = bits(16 * K * bk, 8 * K); // chunk bits [0, 8K) -> steps u 8..15
const uint64_t hi8 = bits(16 * K * bk + 8 * K, 8 * K); // chunk bits [8K, 16K) -> steps u 0..7
win[lane][bk][1] = lo8 | (hi8 & ((1ull << (15 - K)) - 1ull)) << (8 * K); // u 8..15 end at bit 7K + 15 <= 16K - 1
win[lane][bk][0] = hi8; // partner bits added below
}
}
// partner bits: the low 15 - K bits of the chunk of lane ^ 16 (same bk)
for (int lane = 0; lane < 32; ++lane)
for (int bk = 0; bk < 2; ++bk) {
const uint64_t pc = win[lane ^ 16][bk][1] & ((1ull << (8 * K)) - 1ull); // partner chunk bits [0, 8K) (its steps u 8..15)
win[lane][bk][0] |= (pc & ((1ull << (15 - K)) - 1ull)) << (8 * K);
}
for (int bk = 0; bk < 2; ++bk) {
Float8 acc[32] = {};
for (int m = 0; m < 8; ++m) {
Half8 a[32], bh[32], bl[32];
for (int lane = 0; lane < 32; ++lane) {
const int kg = lane / 16;
for (int s2 = 0; s2 < 2; ++s2) {
const int u = 2 * m + s2; // local step 0..15
// u 0..7 live in window 0 at offset (7 - u) K, u 8..15 in window 1 at offset (15 - u) K
const uint32_t st = (uint32_t) ((u < 8 ? win[lane][bk][0] >> ((7 - u) * K) : win[lane][bk][1] >> ((15 - u) * K))) & 0x7fffu;
uint32_t w2[2];
step(st, w2);
a[lane].h[4 * s2 + 0] = (uint16_t) (w2[0] & 0xffffu); a[lane].h[4 * s2 + 1] = (uint16_t) (w2[0] >> 16);
a[lane].h[4 * s2 + 2] = (uint16_t) (w2[1] & 0xffffu); a[lane].h[4 * s2 + 3] = (uint16_t) (w2[1] >> 16);
}
const int n = lane % 16;
for (int j = 0; j < 8; ++j) {
float xv = 0.f;
if (n < nb) xv = x[(size_t) n * in + (2 * P + bk) * 128 + 4 * (16 * kg + 2 * m) + j];
const uint16_t hi = f2h_rn(xv);
bh[lane].h[j] = hi;
bl[lane].h[j] = f2h_rn(xv - tqcode::h2f(hi));
}
}
wmma_f32_16x16x16_f16(a, bh, acc);
if (exact) wmma_f32_16x16x16_f16(a, bl, acc);
}
for (int lane = 0; lane < 32; ++lane)
for (int i = 0; i < 8; ++i) {
const int row = 8 * (lane / 16) + i;
tot[lane][i] += tqcode::h2f(sc[(base * 16 + row) * 2 + bk]) * acc[lane].f[i];
}
}
}
for (int lane = 0; lane < 32; ++lane) {
const int n = lane % 16;
if (n >= nb) continue;
for (int i = 0; i < 8; ++i) y[(size_t) n * rows + t * 16 + 8 * (lane / 16) + i] = tot[lane][i];
}
}
}
} // namespace tqw
+64
View File
@@ -0,0 +1,64 @@
// tools/dsv41_lab/wmma_emu_test.cpp - the gfx12 port's data flow (wmma_emu.hpp) against the double reference on decoded weights.
// ./wmma_emu_test table codebook (shipped K5/K6/K7)
// TQE_CODE=3single ./wmma_emu_test computed code
// Host only; no GPU needed.
#include "../trellis/tqenc.hpp"
#include "wmma_emu.hpp"
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <random>
#include <vector>
static void step_table(uint32_t s, uint32_t out[2]) {
static std::vector<uint32_t> lut;
if (lut.empty()) {
const float* pt = tqenc::point_table();
lut.resize(2048);
for (int i = 0; i < 2048; ++i) lut[i] = tqw::f2h_rn(pt[2 * i]) | ((uint32_t) tqw::f2h_rn(pt[2 * i + 1]) << 16);
}
const uint32_t x = (s & 0x7fffu) * 0x9e3779b1u;
out[0] = lut[x >> 21];
out[1] = lut[(x >> 10) & 2047u];
}
static void step_3single(uint32_t s, uint32_t out[2]) { out[0] = tqcode::word3(s & 0x7fffu, 0); out[1] = tqcode::word3(s & 0x7fffu, 1); }
int main() {
const bool computed = tqcode::kind_of(std::getenv("TQE_CODE")) == tqcode::k3single;
if (std::getenv("TQE_CODE") && !computed) { std::printf("only TQE_CODE=3single is wired here\n"); return 2; }
std::mt19937_64 rng(7);
int fails = 0;
const int Ks[4] = {4, 5, 6, 7}, types[4] = {225, 224, 145, 146};
for (int ki = 0; ki < 4; ++ki) {
const int K = Ks[ki], type = types[ki], bsz = 2 + 4 * K;
const int rows = 48, in = 768, nblk = in / 128;
std::vector<uint8_t> w((size_t) rows * nblk * bsz);
for (auto& b : w) b = (uint8_t) rng();
for (int64_t b = 0; b < (int64_t) rows * nblk; ++b) { const uint16_t d = tqw::f2h_rn(0.02f + 0.001f * (float) (rng() % 400)); std::memcpy(&w[(size_t) b * bsz], &d, 2); }
std::vector<float> dec((size_t) rows * in);
tqenc::decode_blocks(type, w.data(), (int64_t) rows * nblk, dec.data());
std::vector<uint32_t> words; std::vector<uint16_t> sc;
tqw::repack_tqw(K, w.data(), rows, nblk, words, sc);
for (int nb : {1, 3, 5}) {
std::vector<float> x((size_t) nb * in);
std::uniform_real_distribution<float> u(-1.f, 1.f);
for (auto& v : x) v = u(rng);
std::vector<float> y;
tqw::gemv_tqw(K, nb, rows, in, words, sc, x, computed ? step_3single : step_table, y);
double worst = 0;
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); }
worst = std::max(worst, std::fabs(y[(size_t) c * rows + r] - s) / (sa + 1e-30));
}
const bool ok = worst < 3e-7;
std::printf("K=%d nb=%d (%s): emulated gfx12 flow vs double reference %.2e %s\n", K, nb, computed ? "3single" : "table", worst, ok ? "ok" : "FAIL");
fails += !ok;
}
}
std::printf("%s\n", fails ? "FAILED" : "ALL OK");
return fails;
}
+221
View File
@@ -0,0 +1,221 @@
"""tqenc.py - Python side of the trellis encoder (tools/trellis/tqenc.cpp, built to libtqenc.so by
`sh tools/trellis/build.sh lib`): encode / decode blocks of TQ2_T, TQK6, TQK7 and the experimental TQK5X / TQK4X, the
input-only block Hadamard of the DeepSeek plan, and error metrics.
Rows of a tensor are blocks of 128 consecutive weights along the INPUT dimension (the GGUF fastest axis), exactly as the
decoders read them. A tensor of shape [rows, n] (n a multiple of 128) is encoded row by row; the output has
rows * n/128 * block_bytes bytes.
"""
from __future__ import annotations
import ctypes
import os
import pathlib
import numpy as np
TQ2_T, TQK6, TQK7, TQK5X, TQK4X = 144, 145, 146, 224, 225
TYPE_NAMES = {TQ2_T: "TQ2_T", TQK6: "TQK6", TQK7: "TQK7", TQK5X: "TQK5X", TQK4X: "TQK4X"}
TYPE_BY_NAME = {v: k for k, v in TYPE_NAMES.items()}
KBITS = {TQ2_T: 8, TQK6: 6, TQK7: 7, TQK5X: 5, TQK4X: 4}
BLOCK = 128
def block_bytes(t: int) -> int:
return 2 + 4 * KBITS[t]
def bpw(t: int) -> float:
return block_bytes(t) * 8 / BLOCK
_lib = None
def lib() -> ctypes.CDLL:
global _lib
if _lib is None:
cands = [os.environ.get("TQENC_LIB", ""),
str(pathlib.Path(__file__).resolve().parent.parent / "build-tqenc" / "libtqenc.so"),
"libtqenc.so"]
last = None
for c in cands:
if not c:
continue
try:
_lib = ctypes.CDLL(c)
break
except OSError as e:
last = e
if _lib is None:
raise RuntimeError("libtqenc.so not found (sh tools/trellis/build.sh lib): %s" % last)
_lib.tqe_encode.restype = ctypes.c_double
_lib.tqe_encode.argtypes = [ctypes.c_int, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int64, ctypes.c_void_p,
ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_int,
ctypes.c_void_p, ctypes.c_void_p]
_lib.tqe_decode.restype = None
_lib.tqe_decode.argtypes = [ctypes.c_int, ctypes.c_void_p, ctypes.c_int64, ctypes.c_void_p]
return _lib
_hip = None
def hip_lib() -> ctypes.CDLL:
"""libtqenc_hip.so (sh tools/trellis/build.sh hip; run under the box GPU locks, HIP_VISIBLE_DEVICES picks the card)."""
global _hip
if _hip is None:
cands = [os.environ.get("TQENC_HIP_LIB", ""),
str(pathlib.Path(__file__).resolve().parent.parent / "build-tqenc" / "libtqenc_hip.so")]
last = None
for c in cands:
if not c:
continue
try:
_hip = ctypes.CDLL(c)
break
except OSError as e:
last = e
if _hip is None:
raise RuntimeError("libtqenc_hip.so not found: %s" % last)
_hip.tqh_encode.restype = ctypes.c_double
_hip.tqh_encode.argtypes = [ctypes.c_int, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int64, ctypes.c_void_p,
ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_void_p,
ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int]
return _hip
def encode(w: np.ndarray, t: int, h: np.ndarray | None = None, iters: int = 1, ncand: int = 1, exact: int = 0,
scale_tries: int = 1, threads: int = 0, gpu: bool = False):
"""w: float32 array whose last axis is a multiple of 128. Returns (packed uint8 [nblocks, block_bytes],
per-block error float64 [nblocks], total error, stats dict). Error = sum h (w - decoded)^2 (h = 1 if None)."""
w = np.ascontiguousarray(w, dtype=np.float32)
if w.shape[-1] % BLOCK:
raise ValueError("last axis %d is not a multiple of 128" % w.shape[-1])
nb = w.size // BLOCK
out = np.zeros((nb, block_bytes(t)), dtype=np.uint8)
err = np.zeros(nb, dtype=np.float64)
stats = np.zeros(2, dtype=np.int64)
hp = None
if h is not None:
h = np.ascontiguousarray(h, dtype=np.float32)
if h.shape != w.shape:
raise ValueError("importance weights must have the shape of w")
hp = h.ctypes.data
if gpu:
if exact or t == TQ2_T:
raise ValueError("the GPU encoder has no exact search and no TQ2_T")
tot = hip_lib().tqh_encode(t, w.ctypes.data, hp, nb, out.ctypes.data, iters, ncand, scale_tries, 0,
err.ctypes.data, stats.ctypes.data, None, 0)
return out, err, tot, {"nonfinite_blocks": int(stats[0]), "zero_blocks": int(stats[1])}
tot = lib().tqe_encode(t, w.ctypes.data, hp, nb, out.ctypes.data, iters, ncand, exact, scale_tries, threads,
err.ctypes.data, stats.ctypes.data)
return out, err, tot, {"nonfinite_blocks": int(stats[0]), "zero_blocks": int(stats[1])}
def decode(packed: np.ndarray, t: int) -> np.ndarray:
"""packed: uint8 array of whole blocks. Returns float32 [nblocks * 128] (d * codebook)."""
packed = np.ascontiguousarray(packed, dtype=np.uint8)
bb = block_bytes(t)
if packed.size % bb:
raise ValueError("%d bytes is not a whole number of %s blocks" % (packed.size, TYPE_NAMES[t]))
nb = packed.size // bb
out = np.zeros(nb * BLOCK, dtype=np.float32)
lib().tqe_decode(t, packed.ctypes.data, nb, out.ctypes.data)
return out
# ---------------------------------------------------------------------------------------------------- Hadamard
def hadamard_matrix(n: int = BLOCK) -> np.ndarray:
"""The normalized Sylvester-Walsh-Hadamard matrix (entry (-1)^popcount(r & c) / sqrt(n)); symmetric, orthonormal."""
h = np.array([[1.0]])
while h.shape[0] < n:
h = np.block([[h, h], [h, -h]])
return (h / np.sqrt(n)).astype(np.float32)
def make_signs(width: int, seed: int) -> np.ndarray:
"""A reproducible +1/-1 vector (the plan's D). The vector itself, not the seed, is what a file must store."""
r = np.random.default_rng(seed)
return (r.integers(0, 2, size=width) * 2 - 1).astype(np.float32)
def pack_signs(signs: np.ndarray) -> bytes:
return np.packbits((signs > 0).astype(np.uint8), bitorder="little").tobytes()
def unpack_signs(b: bytes, width: int) -> np.ndarray:
bits = np.unpackbits(np.frombuffer(b, dtype=np.uint8), bitorder="little")[:width]
return bits.astype(np.float32) * 2 - 1
def rotate(w: np.ndarray, signs: np.ndarray | None) -> np.ndarray:
"""The input transform U = H D on the last axis, per 128-block: Wrot = W U^T, i.e. each row w -> H (signs * w).
The same function applied to an activation x gives U x."""
w = np.asarray(w, dtype=np.float32)
if signs is not None:
w = w * signs
shp = w.shape
return (w.reshape(-1, BLOCK) @ hadamard_matrix()).reshape(shp) # H is symmetric
def unrotate(w: np.ndarray, signs: np.ndarray | None) -> np.ndarray:
"""Inverse of rotate (H is its own inverse: orthonormal and symmetric; then the signs)."""
shp = w.shape
x = (np.asarray(w, dtype=np.float32).reshape(-1, BLOCK) @ hadamard_matrix()).reshape(shp)
return x * signs if signs is not None else x
# ---------------------------------------------------------------------------------------------------- metrics
def sqnr_db(ref: np.ndarray, approx: np.ndarray) -> float:
ref = np.asarray(ref, dtype=np.float64).ravel()
e = np.sum((ref - np.asarray(approx, dtype=np.float64).ravel()) ** 2)
return float("inf") if e == 0 else float(10 * np.log10(np.sum(ref ** 2) / e))
def rel_mse(ref: np.ndarray, approx: np.ndarray) -> float:
ref = np.asarray(ref, dtype=np.float64).ravel()
return float(np.sum((ref - np.asarray(approx, dtype=np.float64).ravel()) ** 2) / max(np.sum(ref ** 2), 1e-300))
# ---------------------------------------------------------------------------------------------------- .tqx container
# A small versioned file for ONE encoded matrix (research artifacts; not a GGUF). Little endian:
# "TQXP" | u32 version (1) | u32 type id | u32 rows | u32 cols | u32 flags (bit 0: input Hadamard, 128-blocks)
# | u32 n_sign_bytes | sign bits (1 = +1, LSB first, one per input column) | u32 hadamard block (128) | packed blocks
# An unknown version or type is refused before any data is read.
TQX_MAGIC = b"TQXP"
TQX_VERSION = 1
def write_tqx(path, t: int, rows: int, cols: int, packed: np.ndarray, signs: np.ndarray | None) -> None:
import struct
sb = pack_signs(signs) if signs is not None else b""
with open(path, "wb") as f:
f.write(TQX_MAGIC + struct.pack("<IIIIII", TQX_VERSION, t, rows, cols, 1 if signs is not None else 0, len(sb)))
f.write(sb)
f.write(struct.pack("<I", BLOCK))
f.write(np.ascontiguousarray(packed, dtype=np.uint8).tobytes())
def read_tqx(path):
import struct
data = open(path, "rb").read()
if data[:4] != TQX_MAGIC:
raise ValueError("not a TQXP file")
ver, t, rows, cols, flags, nsb = struct.unpack_from("<IIIIII", data, 4)
if ver != TQX_VERSION:
raise ValueError("unsupported TQXP version %d (this reader handles %d)" % (ver, TQX_VERSION))
if t not in KBITS:
raise ValueError("unknown trellis type %d" % t)
at = 4 + 24
signs = unpack_signs(data[at:at + nsb], cols) if flags & 1 else None
at += nsb
(blk,) = struct.unpack_from("<I", data, at)
at += 4
if blk != BLOCK:
raise ValueError("unsupported Hadamard block %d" % blk)
nb = rows * (cols // BLOCK)
packed = np.frombuffer(data, dtype=np.uint8, count=nb * block_bytes(t), offset=at).reshape(nb, block_bytes(t))
return t, rows, cols, packed, signs
+34
View File
@@ -0,0 +1,34 @@
# Trellis encoder (research, branch f-dsv41-enc)
An encoder for the trellis expert formats that Strata already decodes (TQ2_T, TQK6, TQK7 of agentionai's llama.cpp fork)
and for two experimental lower rates, TQK5X (22 bytes per 128 weights, 1.375 bpw) and TQK4X (18 bytes, 1.125 bpw).
Written for the DeepSeek-V4.1-Flash compression plan (gate 2 and the start of gate 3). Nothing here changes an existing
type, layout or default; the engine's CPU decoder only gains K = 5 and 4 (ids 224 / 225, experimental version 1).
| file | what |
| --- | --- |
| `tqenc.hpp`, `tqenc.cpp` | the encoder: tail-biting Viterbi on the 2^15-state shift trellis, fp16 scale refinement, importance weights; a C API |
| `tqenc_test.cpp` | the tests (about 64,000 checks): streams and the circular wrap, Viterbi against a naive DP, planted solutions, bit-exact decode against `tq_states.hpp` and the scalar / AVX2 / AVX-512 kernels, special blocks, thread determinism, quality against the rate-distortion limit |
| `tqenc_hip.cpp`, `tqenc_hip_test.cpp` | the same search on a GPU (HIP, gfx1201): bit-identical blocks, about 20 M weights/s on one R9700 |
| `../tqenc.py` | Python wrapper (ctypes): `encode`, `decode`, the input-only block-128 Hadamard, signs, the `.tqx` container |
| `pilot.py`, `pilot_summary.py` | the block-quality pilot on a source GGUF (local files or HTTP range requests) |
| `gyro_reencode.py`, `gyro_vs_original.py`, `gyro_error_profile.py`, `hf_slice.py` | checks against agentionai's Gyro files and the original Qwen weights |
Build and test (Linux x86-64, g++ with AVX2; the GPU part needs ROCm):
sh tools/trellis/build.sh test && build-tqenc/tqenc_test # --quick skips the quality table
sh tools/trellis/build.sh lib && python3 tools/trellis/test_tqenc_py.py
sh tools/trellis/build.sh hip && HIP_VISIBLE_DEVICES=3 build-tqenc/tqenc_hip_test
`build.sh hip` compiles `tqenc.cpp` with g++ on purpose: under hipcc, `ggml-common-tq.h` turns its codebook into a
`__device__` variable and the host side reads zeros.
## Format facts the encoder relies on (checked against the decoder, not the comments)
* A block is `{fp16 d; 4K bytes}` for 128 weights: 32 steps, step t gives weights 4t..4t+3.
* State of step t: 15 bits. TQK: the 16-bit window of the stream at bit `(31 - t) K` (LSB first, circular modulo 32 K bits), masked
to 15 bits. TQ2_T: `(qs[(t+31)%32] << 8 | qs[t]) & 0x7fff`.
* Weights of a step: `x = state * 0x9e3779b1`, the two codebook points `lut[x >> 21]` and `lut[(x >> 10) & 2047]`, times d. The
decoder's table is `round(fp16 * 8192)`; the encoder uses that table, so its reconstruction is the decoder's, bit for bit.
* A legal stream is any byte string (every state is a window of the same circular stream); tail-biting only matters to the search.
* K5 and K4 are the TQK rule with K = 5 and 4. Nothing else changes (hash, codebook, mask, bit order, scale).
+29
View File
@@ -0,0 +1,29 @@
#!/bin/sh
# tools/trellis/build.sh [test|lib|bench] - builds the trellis encoder standalone (g++, Linux x86-64).
# Run from the repository root. Output in ${TQ_OUT:-build-tqenc}.
set -e
OUT=${TQ_OUT:-build-tqenc}
mkdir -p "$OUT"
CXX=${CXX:-g++}
INC="-Itools/trellis -Iinclude -Isrc/kernels/cpu -Ithird_party/ggml"
OPT="-O3 -std=c++17 -mavx2 -mfma -mf16c -fno-fast-math -pthread"
case "${1:-test}" in
lib)
$CXX $OPT -fPIC -shared $INC tools/trellis/tqenc.cpp -o "$OUT/libtqenc.so" ;;
hip)
# needs the ROCm of /data/dsv41/rv: export ROCM_PATH=/data/dsv41/rv/lib/python3.14/site-packages/_rocm_sdk_devel PATH=/data/dsv41/rv/bin:$PATH
# the host part of the encoder (tqenc.cpp) is built by g++: under hipcc ggml-common-tq.h's table becomes a __device__ variable
g++ $OPT -fPIC $INC -c tools/trellis/tqenc.cpp -o "$OUT/tqenc_host.o"
HF="-O3 --offload-arch=gfx1201 -mcumode -std=c++17 -mavx2 -mfma -mf16c"
hipcc $HF -fPIC $INC -c tools/trellis/tqenc_hip.cpp -o "$OUT/tqenc_hip.o"
hipcc $HF $INC -c tools/trellis/tqenc_hip_test.cpp -o "$OUT/tqenc_hip_test.o"
hipcc --offload-arch=gfx1201 "$OUT/tqenc_hip_test.o" "$OUT/tqenc_hip.o" "$OUT/tqenc_host.o" -o "$OUT/tqenc_hip_test"
hipcc --offload-arch=gfx1201 -shared "$OUT/tqenc_hip.o" "$OUT/tqenc_host.o" -o "$OUT/libtqenc_hip.so" ;;
test)
$CXX $OPT $INC -c src/kernels/cpu/tq_cpu.cpp -o "$OUT/tq_cpu.o"
$CXX $OPT $INC -c src/kernels/cpu/tq_avx2.cpp -o "$OUT/tq_avx2.o"
$CXX -O3 -std=c++17 -mavx512f -mavx512bw -mavx512vl -mavx512vbmi -mavx512vnni -mfma -mf16c -mavx2 $INC -c src/kernels/cpu/tq_avx512.cpp -o "$OUT/tq_avx512.o"
$CXX $OPT $INC tools/trellis/tqenc_test.cpp tools/trellis/tqenc.cpp "$OUT/tq_cpu.o" "$OUT/tq_avx2.o" "$OUT/tq_avx512.o" -o "$OUT/tqenc_test"
;;
esac
echo built "$OUT"
+94
View File
@@ -0,0 +1,94 @@
"""hf_slice.py - read single tensors (or slices of them) out of a remote safetensors repo with HTTP range requests, so a
quality test needs megabytes of a model, not the model. No token is read or printed (public repos only; set HF_TOKEN in
the environment for gated ones - it is sent as a header and never printed).
from hf_slice import Repo
r = Repo("Qwen/Qwen3.8-Flash-Next")
w = r.tensor("model.language_model.layers.0.mlp.experts.gate_up_proj", rows=slice(0, 1)) # expert 0 only
"""
from __future__ import annotations
import concurrent.futures as cf
import json
import os
import struct
import urllib.request
import numpy as np
_DT = {"BF16": (2, None), "F16": (2, np.float16), "F32": (4, np.float32), "F8_E4M3": (1, None), "I8": (1, np.int8),
"U8": (1, np.uint8), "I32": (4, np.int32), "I64": (8, np.int64)}
def _get(url: str, start: int | None = None, end: int | None = None) -> bytes:
req = urllib.request.Request(url)
tok = os.environ.get("HF_TOKEN")
if tok:
req.add_header("Authorization", "Bearer " + tok)
if start is not None:
req.add_header("Range", "bytes=%d-%d" % (start, end))
with urllib.request.urlopen(req, timeout=120) as r:
return r.read()
def get_parallel(url: str, start: int, end: int, workers: int = 16, piece: int = 8 << 20) -> bytes:
"""bytes start..end (inclusive) of url, in `piece`-byte range requests on `workers` threads (one stream of a CDN
object is slow, a dozen are not)."""
spans = [(a, min(end, a + piece - 1)) for a in range(start, end + 1, piece)]
if len(spans) == 1:
return _get(url, start, end)
def one(sp):
for attempt in range(6):
try:
return _get(url, sp[0], sp[1])
except Exception:
if attempt == 5:
raise
return b""
with cf.ThreadPoolExecutor(workers) as ex:
return b"".join(ex.map(one, spans))
def bf16_to_f32(raw: bytes | np.ndarray) -> np.ndarray:
u = np.frombuffer(raw, dtype=np.uint16).astype(np.uint32) << 16
return u.view(np.float32)
class Repo:
def __init__(self, repo: str, rev: str = "main"):
self.repo, self.rev = repo, rev
self.base = "https://huggingface.co/%s/resolve/%s/" % (repo, rev)
self.map = json.loads(_get(self.base + "model.safetensors.index.json"))["weight_map"]
self._hdr: dict[str, tuple[dict, int]] = {}
def header(self, shard: str):
if shard not in self._hdr:
n = struct.unpack("<Q", _get(self.base + shard, 0, 7))[0]
h = json.loads(_get(self.base + shard, 8, 8 + n - 1))
self._hdr[shard] = (h, 8 + n)
return self._hdr[shard]
def info(self, name: str):
shard = self.map[name]
h, base = self.header(shard)
return shard, h[name], base
def tensor(self, name: str, lead: slice | int | None = None, workers: int = 16) -> np.ndarray:
"""The tensor `name` as float32. lead: an index or slice on the first axis (e.g. an expert), fetched alone."""
shard, t, base = self.info(name)
shape = t["shape"]
item = _DT[t["dtype"]][0]
s, e = t["data_offsets"]
inner = int(np.prod(shape[1:])) * item if len(shape) > 1 else item
if lead is None:
i0, i1 = 0, shape[0]
elif isinstance(lead, int):
i0, i1 = lead, lead + 1
else:
i0, i1 = lead.start or 0, lead.stop
raw = get_parallel(self.base + shard, base + s + i0 * inner, base + s + i1 * inner - 1, workers)
out_shape = [i1 - i0] + shape[1:]
if t["dtype"] == "BF16":
return bf16_to_f32(raw).reshape(out_shape)
return np.frombuffer(raw, dtype=_DT[t["dtype"]][1]).astype(np.float32).reshape(out_shape)
+228
View File
@@ -0,0 +1,228 @@
"""pilot.py - gate-3 block-quality pilot: a few experts from several layers of a source checkpoint, encoded at TQK4X / TQK5X /
TQK6 / TQK7 with and without the input-only block-128 Hadamard, and measured.
Sources: --gguf <shard1 or shard dir files...> (UD-Q8_K_XL: MXFP4 / Q8_0 / BF16 / F16 tensors, decoded exactly: the decoded
source is the teacher, as the plan says) or --hf Qwen/... (range requests; test of the pipeline)
Metrics per (layer, role, expert, rate, transform), over a random row subset of the projection (--rows):
mse relative weight MSE ||W - W^||^2 / ||W||^2 in the original basis (the Hadamard is orthonormal: the same in either basis)
act_iso ||(W - W^) X||^2 / ||W X||^2 with X i.i.d. N(0,1) columns - PLACEHOLDER; in expectation equal to mse
act_syn ||(W - W^) X||^2 / ||W X||^2 with X whose input channels have heavy-tailed scales (a few outlier channels,
log-normal rest) - SYNTHETIC PLACEHOLDER for real calibration activations, labelled as such in every output
Real activation-weighted numbers need calibration activations from the reference runtime (not done here).
"""
from __future__ import annotations
import argparse
import json
import mmap
import pathlib
import sys
import time
import numpy as np
HERE = pathlib.Path(__file__).resolve().parent
sys.path.insert(0, str(HERE.parent))
sys.path.insert(0, str(HERE))
import gguf_reader # noqa: E402
import tqenc # noqa: E402
MXFP4_LUT = np.array([0, 1, 2, 3, 4, 6, 8, 12, 0, -1, -2, -3, -4, -6, -8, -12], dtype=np.float32)
RATES = {"K4": tqenc.TQK4X, "K5": tqenc.TQK5X, "K6": tqenc.TQK6, "K7": tqenc.TQK7}
CFGS = {
"fast": dict(iters=0, ncand=1, scale_tries=1),
"default": dict(iters=1, ncand=1, scale_tries=1),
"rot3": dict(iters=3, ncand=3, scale_tries=1),
}
def decode_mxfp4(raw: np.ndarray, n_in: int) -> np.ndarray:
"""raw: [rows * n_in/32 * 17] bytes -> float32 [rows, n_in]. ggml block_mxfp4: e8m0 scale, 16 bytes, low nibble =
element j, high nibble = element j + 16, value = kvalues[nibble] * 2^(e - 128) (the e8m0 half scale)."""
b = raw.reshape(-1, 17)
e = b[:, 0].astype(np.int32)
d = np.where(e == 0, np.float32(2.0 ** -127), np.ldexp(np.float32(1.0), e - 128)).astype(np.float32)
q = b[:, 1:]
vals = np.concatenate([MXFP4_LUT[q & 15], MXFP4_LUT[q >> 4]], axis=1) * d[:, None]
return vals.reshape(-1, n_in)
def decode_q8_0(raw: np.ndarray, n_in: int) -> np.ndarray:
b = raw.reshape(-1, 34)
d = b[:, :2].copy().view(np.float16).astype(np.float32)
q = b[:, 2:].copy().view(np.int8).astype(np.float32)
return (q * d).reshape(-1, n_in)
class Source:
"""Yields float32 [rows, n_in] row subsets of one expert's projection. Local GGUF files (mmap) or, with
remote=(repo, rev, [shard paths]), the same files read by HTTP range requests (headers and the few experts needed)."""
def __init__(self, gguf_paths=None, remote=None, tmpdir="/tmp"):
self.tensors = {}
if gguf_paths:
for p in gguf_paths:
g = gguf_reader.GGUFFile(p)
fh = open(p, "rb")
mm = mmap.mmap(fh.fileno(), 0, access=mmap.ACCESS_READ)
for t in g.tensors:
self.tensors[t.name] = (g, (lambda off, n, mm=mm: np.frombuffer(mm, dtype=np.uint8, count=n, offset=off)), t)
if remote:
import urllib.request
repo, rev, shards = remote
for sh in shards:
url = "https://huggingface.co/%s/resolve/%s/%s" % (repo, rev, sh)
def rd(off, n, url=url):
req = urllib.request.Request(url, headers={"Range": "bytes=%d-%d" % (off, off + n - 1)})
with urllib.request.urlopen(req, timeout=300) as r:
return np.frombuffer(r.read(), dtype=np.uint8)
hdr = rd(0, 6 << 20)
tp = pathlib.Path(tmpdir) / ("hdr_%s" % pathlib.Path(sh).name)
tp.write_bytes(hdr.tobytes())
g = gguf_reader.GGUFFile(tp)
for t in g.tensors:
self.tensors[t.name] = (g, rd, t)
def names(self, needle):
return sorted(n for n in self.tensors if needle in n)
def expert_rows(self, name: str, expert: int, rows: np.ndarray) -> np.ndarray:
g, rd, ti = self.tensors[name]
n_in, n_out = ti.shape[0], ti.shape[1]
if ti.type_name == "MXFP4":
rb = n_in // 32 * 17
elif ti.type_name == "Q8_0":
rb = n_in // 32 * 34
elif ti.type_name in ("BF16", "F16"):
rb = n_in * 2
elif ti.type_name == "F32":
rb = n_in * 4
else:
raise ValueError("%s: tensor type %s is not readable by this pilot" % (name, ti.type_name))
base = g.data_start + ti.offset + expert * n_out * rb
whole = rd(base, n_out * rb) # one expert's projection (6.3 MB for MXFP4 2304 x 5120), then the row subset
out = np.empty((len(rows), n_in), dtype=np.float32)
for k, r in enumerate(rows):
raw = whole[int(r) * rb:(int(r) + 1) * rb]
if ti.type_name == "MXFP4":
out[k] = decode_mxfp4(raw, n_in)[0]
elif ti.type_name == "Q8_0":
out[k] = decode_q8_0(raw, n_in)[0]
elif ti.type_name == "BF16":
out[k] = (raw.view(np.uint16).astype(np.uint32) << 16).view(np.float32)
elif ti.type_name == "F16":
out[k] = raw.view(np.float16).astype(np.float32)
else:
out[k] = raw.view(np.float32)
return out
def synth_x(n_in: int, T: int, seed: int) -> np.ndarray:
"""SYNTHETIC activations: channel scale exp(N(0, 0.5)), 1% of the channels x (10..40)."""
r = np.random.default_rng(seed)
s = np.exp(0.5 * r.standard_normal(n_in)).astype(np.float32)
out = r.choice(n_in, size=max(1, n_in // 100), replace=False)
s[out] *= r.uniform(10, 40, size=out.size).astype(np.float32)
return (r.standard_normal((n_in, T)).astype(np.float32) * s[:, None])
def act_err(W, What, X):
D = (W - What).astype(np.float32) @ X
Y = W.astype(np.float32) @ X
return float(np.sum(D.astype(np.float64) ** 2) / max(np.sum(Y.astype(np.float64) ** 2), 1e-300))
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--gguf", nargs="+", default=None)
ap.add_argument("--remote", default=None, help="REPO@REV: read the shards named in --shards by HTTP range requests")
ap.add_argument("--shards", nargs="+", default=[])
ap.add_argument("--layers", default="1,7,14,21,30,38")
ap.add_argument("--experts", default="0,97,200,383")
ap.add_argument("--roles", default="gate,up,down")
ap.add_argument("--rates", default="K4,K5,K6,K7")
ap.add_argument("--rows", type=int, default=256)
ap.add_argument("--tokens", type=int, default=256, help="columns of the placeholder X")
ap.add_argument("--cfg", default="default")
ap.add_argument("--threads", type=int, default=0)
ap.add_argument("--out", required=True, help="jsonl results")
ap.add_argument("--seed", type=int, default=1)
ap.add_argument("--pattern", default="blk.{L}.ffn_{R}_exps.weight")
ap.add_argument("--gpu", action="store_true", help="encode on the GPU (run under the box locks, HIP_VISIBLE_DEVICES)")
ap.add_argument("--act-diag-dir", default=None,
help="directory with L<layer>_<role>.npy = E[x^2] per input channel of that projection (calibration "
"second moments, diagonal). Adds act_diag (the exact diagonal-Hessian error) and an importance-weighted "
"encode (h = E[x^2]; in the Hadamard basis h = the block average of it)")
a = ap.parse_args()
if a.remote:
repo, rev = a.remote.split("@")
src = Source(remote=(repo, rev, a.shards))
else:
src = Source(a.gguf)
rng = np.random.default_rng(a.seed)
cfg = CFGS[a.cfg]
sign_cache, x_cache = {}, {}
out = open(a.out, "a")
for layer in [int(x) for x in a.layers.split(",")]:
for role in a.roles.split(","):
name = a.pattern.format(L=layer, R=role)
if name not in src.tensors:
print("no tensor", name, "(have e.g. %s)" % src.names("exps")[:3])
continue
g, rd, ti = src.tensors[name]
n_in, n_out, n_exp = ti.shape[0], ti.shape[1], ti.shape[2]
for e in [int(x) for x in a.experts.split(",")]:
if e >= n_exp:
continue
rows = np.sort(rng.choice(n_out, size=min(a.rows, n_out), replace=False))
W = src.expert_rows(name, e, rows)
en = float(np.sum(W.astype(np.float64) ** 2))
if n_in not in sign_cache:
sign_cache[n_in] = tqenc.make_signs(n_in, 1000 + n_in)
x_cache[n_in] = (np.random.default_rng(7).standard_normal((n_in, a.tokens)).astype(np.float32),
synth_x(n_in, a.tokens, 9))
Xi, Xs = x_cache[n_in]
diag = None
if a.act_diag_dir:
dp = pathlib.Path(a.act_diag_dir) / ("L%d_%s.npy" % (layer, role))
if dp.exists():
diag = np.load(dp).astype(np.float64)
assert diag.shape == (n_in,), (dp, diag.shape)
for had in (False, True):
sg = sign_cache[n_in] if had else None
Wr = tqenc.rotate(W, sg) if had else W
for rname in a.rates.split(","):
t = RATES[rname]
t0 = time.time()
packed, err, tot, st = tqenc.encode(Wr, t, threads=a.threads, gpu=a.gpu, **cfg)
sec = time.time() - t0
dec = tqenc.decode(packed, t).reshape(Wr.shape)
What = tqenc.unrotate(dec, sg) if had else dec
rec = dict(layer=layer, role=role, expert=e, rate=rname, had=had, n_in=n_in, rows=len(rows),
mse=float(np.sum((W.astype(np.float64) - What) ** 2) / en),
act_iso=act_err(W, What, Xi), act_syn=act_err(W, What, Xs),
bpw=tqenc.bpw(t), seconds=sec, zero_blocks=st["zero_blocks"], cfg=a.cfg,
x_kind="placeholder: iso gaussian / synthetic outlier channels")
if diag is not None:
hv = np.maximum(diag, 1e-30).astype(np.float32)
rec["act_diag"] = float(np.sum(((W - What).astype(np.float64) ** 2) * hv) / np.sum((W.astype(np.float64) ** 2) * hv))
hb = hv if not had else np.repeat(hv.reshape(-1, 128).mean(axis=1), 128)
hw = np.broadcast_to(hb, Wr.shape).astype(np.float32)
packed2, _, _, _ = tqenc.encode(Wr, t, h=hw, threads=a.threads, gpu=a.gpu, **cfg)
dec2 = tqenc.decode(packed2, t).reshape(Wr.shape)
What2 = tqenc.unrotate(dec2, sg) if had else dec2
rec["act_diag_weighted_encode"] = float(np.sum(((W - What2).astype(np.float64) ** 2) * hv) / np.sum((W.astype(np.float64) ** 2) * hv))
rec["mse_weighted_encode"] = float(np.sum((W.astype(np.float64) - What2) ** 2) / en)
out.write(json.dumps(rec) + "\n")
out.flush()
print("L%-3d %-4s e%-3d %s %-5s mse %.4f (%.2f dB) act_iso %.4f act_syn %.4f %.1fs" % (
layer, role, e, rname, "had" if had else "plain", rec["mse"], -10 * np.log10(rec["mse"]),
rec["act_iso"], rec["act_syn"], sec), flush=True)
return 0
if __name__ == "__main__":
sys.exit(main())
+42
View File
@@ -0,0 +1,42 @@
"""pilot_summary.py - tables from the jsonl of pilot.py.
python3 tools/trellis/pilot_summary.py pilot1.jsonl
"""
import collections
import json
import math
import sys
rows = [json.loads(l) for l in open(sys.argv[1])]
print("records:", len(rows), "layers:", sorted({r["layer"] for r in rows}), "experts:", sorted({r["expert"] for r in rows}),
"rows per matrix:", sorted({r["rows"] for r in rows}))
print("activation columns are PLACEHOLDERS (iso gaussian / synthetic outlier channels), not calibration data\n")
def db(x):
return -10 * math.log10(x)
def table(keyf, title, cols=("mse", "act_iso", "act_syn")):
g = collections.defaultdict(list)
for r in rows:
g[keyf(r)].append(r)
print(title)
for k in sorted(g):
v = g[k]
print(" %-40s n=%-3d " % (k, len(v)) + " ".join("%s %.4f (%.2f dB)" % (c, sum(x[c] for x in v) / len(v), db(sum(x[c] for x in v) / len(v))) for c in cols))
print()
rate_bpw = {"K4": 1.125, "K5": 1.375, "K6": 1.625, "K7": 1.875}
table(lambda r: "%s %.3f bpw %s" % (r["rate"], rate_bpw[r["rate"]], "hadamard" if r["had"] else "plain "), "mean over everything")
table(lambda r: "%s %s %s" % (r["role"], r["rate"], "had" if r["had"] else "plain"), "by projection")
table(lambda r: "L%02d %s %s" % (r["layer"], r["rate"], "had" if r["had"] else "plain"), "by layer")
# spread of the weight mse across experts for K5 plain
v = [r["mse"] for r in rows if r["rate"] == "K5" and not r["had"]]
print("K5 plain weight mse over all %d matrices: min %.4f max %.4f" % (len(v), min(v), max(v)))
# hadamard gain on the synthetic outlier activations
print("\nHadamard effect on act_syn (relative error, plain / hadamard), per rate")
for rate in ("K4", "K5", "K6", "K7"):
a = [r["act_syn"] for r in rows if r["rate"] == rate and not r["had"]]
b = [r["act_syn"] for r in rows if r["rate"] == rate and r["had"]]
print(" %s plain %.4f had %.4f ratio %.3f" % (rate, sum(a) / len(a), sum(b) / len(b), (sum(a) / len(a)) / (sum(b) / len(b))))
+590
View File
@@ -0,0 +1,590 @@
// tools/trellis/tqenc.cpp - see tqenc.hpp.
#include "tqenc.hpp"
#include "ggml-common-tq.h"
#include "../dsv41_lab/computed_codes.hpp"
#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];
double cb_rms = 1.072;
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);
}
}
// research hook (tools/dsv41_lab/computed_codes.hpp): TQE_CODE=1mad|3inst|3sum|3single replaces the table by a computed
// LUT-free code (the same shift trellis, the same search); cb_rms then is the code's own rms
if (tqcode::Kind k = tqcode::kind_of(std::getenv("TQE_CODE")); k != tqcode::kNone) {
double ss = 0;
for (uint32_t s = 0; s < (uint32_t) kStates; ++s) {
float v[4];
tqcode::code4(k, s, v);
for (int j = 0; j < 4; ++j) { soa[j][s] = v[j]; ss += (double) v[j] * v[j]; tab[4 * s + j] = (int16_t) std::lround(std::max(-32767.0, std::min(32767.0, v[j] * 8192.0))); }
}
cb_rms = std::sqrt(ss / (4.0 * kStates));
}
}
};
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
const double kCbRms = cb().cb_rms;
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(); }
}
+96
View File
@@ -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