Skip to content

Run frontier MoE models on hardware you already own — pure C, zero deps, experts streamed from disk. Tiny engine, immense model. 🐦

C

CPU: KV cache quantization — KV8 (fp8 e4m3) + KV_TQ (rotated-int4 / PolarQuant)

recviking11197828bc83
diff --git a/c/.gitignore b/c/.gitignore
index ed6d0910..07f08c0b 100644
--- a/c/.gitignore
+++ b/c/.gitignore
@@ -28,6 +28,7 @@ tests/test_i4_grouped
tests/test_kv_alloc
tests/test_kv_disk
tests/test_kv_fp8
+tests/test_kv_tq
tests/test_logit_nan
tests/test_sample_nan
tests/test_stops
diff --git a/c/Makefile b/c/Makefile
index 1c6e742d..f86fc141 100644
--- a/c/Makefile
+++ b/c/Makefile
@@ -681,7 +681,7 @@ $(file >.build-config,$(BUILD_CONFIG))
endif
.build-config: ;
-colibri$(EXE): colibri.c st.h uring.h json.h tok.h tok_unicode.h compat.h grammar.h quant.h sample.h kv_persist.h telemetry.h route_trace.h omp_tune.h $(CUDA_OBJ) $(METAL_OBJ) $(VK_OBJ) $(VK_SPV) .build-config
+colibri$(EXE): colibri.c st.h uring.h json.h tok.h tok_unicode.h compat.h grammar.h quant.h sample.h kv_persist.h telemetry.h route_trace.h omp_tune.h kv_fp8.h kv_tq.h $(CUDA_OBJ) $(METAL_OBJ) $(VK_OBJ) $(VK_SPV) .build-config
$(CC) $(CFLAGS) colibri.c $(CUDA_OBJ) $(METAL_OBJ) $(VK_OBJ) -o colibri$(EXE) $(LDFLAGS)
# Vulkan backend object (plain C + vulkan headers) and its SPIR-V shaders.
@@ -1140,7 +1140,16 @@ tests/test_sample_nan$(EXE): tests/test_sample_nan.c colibri.c st.h uring.h json
tests/test_temp_env$(EXE): tests/test_temp_env.c colibri.c st.h uring.h json.h tok.h tok_unicode.h compat.h grammar.h tier.h quant.h sample.h kv_persist.h telemetry.h route_trace.h
$(CC) $(CFLAGS) $< -o $@ $(LDFLAGS)
-tests/test_kv_alloc$(EXE): tests/test_kv_alloc.c colibri.c st.h json.h tok.h tok_unicode.h compat.h grammar.h tier.h quant.h sample.h kv_persist.h telemetry.h route_trace.h
+tests/test_kv_alloc$(EXE): tests/test_kv_alloc.c colibri.c st.h json.h tok.h tok_unicode.h compat.h grammar.h tier.h quant.h sample.h kv_persist.h telemetry.h route_trace.h kv_fp8.h kv_tq.h
+ $(CC) $(CFLAGS) $< -o $@ $(LDFLAGS)
+
+tests/test_kv_fp8$(EXE): tests/test_kv_fp8.c kv_fp8.h decode_batch.h
+ $(CC) $(CFLAGS) $< -o $@ $(LDFLAGS)
+
+tests/test_kv_tq$(EXE): tests/test_kv_tq.c kv_tq.h
+ $(CC) $(CFLAGS) $< -o $@ $(LDFLAGS)
+
+tests/test_kv_disk$(EXE): tests/test_kv_disk.c colibri.c st.h json.h tok.h tok_unicode.h compat.h grammar.h tier.h quant.h sample.h kv_persist.h telemetry.h route_trace.h kv_fp8.h kv_tq.h
$(CC) $(CFLAGS) $< -o $@ $(LDFLAGS)
# fmt=6 kernel oracle: needs the generated grid table, and its fixture comes from
diff --git a/c/colibri.c b/c/colibri.c
index bd1fbe4a..4933e483 100644
--- a/c/colibri.c
+++ b/c/colibri.c
@@ -68,6 +68,8 @@
#include "schema_gbnf.h" /* SCHEMA=: JSON-Schema -> GBNF for method F */
#include "decode_batch.h"
#include "route_trace.h" /* ROUTE_TRACE + .coli_usage, engine-agnostic (#700) */
+#include "kv_fp8.h" /* KV8=1: cache latente in fp8 e4m3 + scala per-riga */
+#include "kv_tq.h" /* KV_TQ=3|4: cache latente PolarQuant (rot+polare) */
#ifdef _OPENMP
#include <omp.h> /* scratch per-thread nell'attention */
#else
@@ -413,6 +415,8 @@ static int eslot_lru_victim(ESlot *slots,int n,int ecap){
typedef struct {
float **Lc, **Rc, **Ic;
+ uint8_t **Lc8, **Rc8; /* KV8: righe latenti fp8 e4m3 (Lc/Rc restano NULL) */
+ float **Lsc, **Rsc; /* KV8: scala amax/448 per riga (per token, per layer) */
int *kv_start, max_t;
int disk_nrec;
char disk_path[2048];
@@ -435,6 +439,7 @@ typedef struct {
* k_rot [qk_rope] (576 vs 32768 valori/token). k_nope e value si ricostruiscono al
* volo con kv_b. E' cio' che rende gestibile il contesto su 15 GB (64 teste, no GQA). */
float **Lc, **Rc; int max_t; /* alias della KVState attiva */
+ uint8_t **Lc8, **Rc8; float **Lsc, **Rsc; /* alias KV8 (fp8 + scale) della KVState attiva */
int *kv_start; /* prima pos valida nella KV del layer (MTP: parziale) */
KVState *kv;
ESlot **ecache; int *ecn; int ecap; /* LRU expert per-layer */
@@ -1322,6 +1327,10 @@ static int g_disk_split=0; /* DISK_SPLIT=1: contatori che spezzano i DISK LOAD (
* non vengono stampate. Solo misura: nessun effetto sull'output. */
#include "sample.h"
+/* KV-cache quantization tier flags — defined here (before kv_persist.h) so the .coli_kv
+ * disk format can see them; the full rationale comments live at their original site below. */
+static int g_kv8=0; /* KV8=1: fp8 e4m3 latent KV + per-row scale */
+static int g_tq=0, g_tq_bits=4, g_tq_codec=1; /* KV_TQ: codec 1=rotated int4 (default), 0=PolarQuant */
#include "kv_persist.h"
#include "telemetry.h"
@@ -3668,6 +3677,17 @@ static void qt_matvec_rows(const QT *t, int r0, int n, const float *x, float *y)
}
static int g_absorb=-1;
static int g_metal_prefill=0; /* default 0: S>4 prefill attention stays on the CPU (bit-exact). COLI_METAL_PREFILL=1 opts it onto the GPU (~4x, near-tie divergence — see docs/metal.md, #622) */
+/* KV8=1: cache latente Lc/Rc in fp8 e4m3 + scala f32 per riga (~4x meno RAM del f32).
+ * CPU-only in this PR — sui percorsi CUDA/Metal che leggono righe f32 si spegne da
+ * solo (guardie !g_kv8), e forza COLI_CUDA_PIPE=0 (il pipe-prefill legge righe f32).
+ * I kernel nativi CUDA/Metal arrivano nei follow-up con hardware owner. */
+/* g_kv8 defined before the kv_persist.h include (above). */
+/* KV_TQ=3|4: tier TurboQuant/PolarQuant (rotazione Hadamard randomizzata +
+ * trasformata polare ricorsiva; raggio = norma L2 nella scala per-riga, solo gli
+ * angoli nei byte). CPU-only, come KV8: si spegne dove i percorsi leggono righe
+ * f32. Mutuamente esclusivo con KV8. Riusa Lc8/Rc8 (byte impacchettati, righe di
+ * coli_kvq_row_bytes) + Lsc/Rsc (raggio f32 per riga). g_tq_bits = livello-1 (3 o 4). */
+/* g_tq, g_tq_bits, g_tq_codec defined before the kv_persist.h include (above). */
#ifdef COLI_CUDA
static int g_cuda_pipe=0; /* COLI_CUDA_PIPE=1: prefill attention chain resident on the layer home device */
static int g_cuda_router=0; /* COLI_CUDA_ROUTER=1 (#431 PR-A): router on the layer home device at decode */
@@ -3955,6 +3975,9 @@ static void attention_rows(Model *m, Layer *l, int layer, float *x, int S, int p
* would rope every row at position 0 and attend over a 1-token window of the wrong
* cache -> greedy decode hits EOS at token 2 (mux answers truncated to 1 token).
* Ragged rows take the CPU absorb path below, which reads kvs[s]/positions[s].
+ * QUANT GUARD (!g_kv8&&!g_tq): the fused kernel reads f32 Lc/Rc rows, which are not
+ * even allocated under KV8/KV_TQ (byte caches + per-row scales instead). Quantized
+ * KV takes the CPU absorb path below; the fp8/TQ Metal kernels are the follow-up PR.
* metal_fused_layer_fmt_miss & METAL_FUSED_ATTN_TENSORS: kv_b on its
* two-format+mode term (fmt==2, or fmt==4 with g_moe_exact off) plus the
* POSITIVE allowlist (fmt 1/2/3/4) over q_a/q_b/kv_a/o -- see the shared
@@ -3975,7 +3998,7 @@ static void attention_rows(Model *m, Layer *l, int layer, float *x, int S, int p
* (its absorb kernel is int4-only, grouped served only outside MOE-exact
* mode); the four allowlist checks are the same discipline extended to
* the tensors that flow through the shared per-fmt shader. */
- if(g_metal_enabled && !kvs && g_absorb!=0 && (S<=4 || g_metal_prefill) && m->kv_start[layer]==0
+ if(g_metal_enabled && !kvs && !g_kv8 && !g_tq && g_absorb!=0 && (S<=4 || g_metal_prefill) && m->kv_start[layer]==0
&& D==6144 && H==64 && c->q_lora==2048 && c->kv_lora==512 && c->qk_nope==192
&& c->qk_rope==64 && vh==256
&& !(metal_fused_layer_fmt_miss(l) & METAL_FUSED_ATTN_TENSORS)){
@@ -4090,7 +4113,10 @@ static void attention_rows(Model *m, Layer *l, int layer, float *x, int S, int p
* cache is _Thread_local, so the positions are independent -> parallelizing is
* byte-identical regardless of order. Only the CUDA/VULKAN shadow-shrink writes
* touch shared state (m->kv_dev_valid/vk_kv_valid), so the pragma is gated to
- * CPU-only builds where those blocks compile out; on GPU builds this stays serial. */
+ * CPU-only builds where those blocks compile out; on GPU builds this stays serial.
+ * (dev's structure supersedes the PR's pre-loop shrink hoist: same goal, and the
+ * KV8/KV_TQ producers below ride the same parallel loop — ~576 libm encodes per
+ * row per layer under KV8 want the OMP pool awake during prefill.) */
if(!pipe_done){
#if !defined(COLI_CUDA) && !defined(COLI_VULKAN)
#pragma omp parallel for schedule(static) if(S > 1)
@@ -4101,8 +4127,6 @@ static void attention_rows(Model *m, Layer *l, int layer, float *x, int S, int p
float *qfull=Q+(int64_t)s*H*qh;
for(int h=0;h<H;h++) rope_interleave(qfull+(int64_t)h*qh+c->qk_nope, pos, c);
const float *cs=comp+(int64_t)s*cw;
- float *Ldst=coli_kv_row(ks->Lc[layer],pos,c->kv_lora);
- float *Rdst=coli_kv_row(ks->Rc[layer],pos,c->qk_rope);
#ifdef COLI_CUDA
if(ks==m->kv&&m->kv_dev_valid&&layer<=c->n_layers&&m->kv_dev_valid[layer]>pos)
m->kv_dev_valid[layer]=pos; /* riga riscritta: l'ombra si accorcia */
@@ -4111,10 +4135,30 @@ static void attention_rows(Model *m, Layer *l, int layer, float *x, int S, int p
if(ks==m->kv&&m->vk_kv_valid&&layer<=c->n_layers&&m->vk_kv_valid[layer]>pos)
m->vk_kv_valid[layer]=pos; /* riga riscritta: la cache VK si accorcia */
#endif
- memcpy(Ldst, cs, c->kv_lora*sizeof(float));
- rmsnorm(Ldst, Ldst, l->kv_a_ln, c->kv_lora, c->eps); /* latente normato */
- memcpy(Rdst, cs+c->kv_lora, c->qk_rope*sizeof(float));
- rope_interleave(Rdst, pos, c); /* k_rot roped, condiviso fra teste */
+ if(g_tq){
+ /* KV_TQ: stessa norma+rope del produttore, poi PolarQuant. Il raggio
+ * (norma L2) va nella scala per-riga (Lsc/Rsc); solo gli angoli nei byte. */
+ float *Ls=comp+(int64_t)s*cw, *Rs=Ls+c->kv_lora;
+ rmsnorm(Ls, Ls, l->kv_a_ln, c->kv_lora, c->eps);
+ rope_interleave(Rs, pos, c);
+ ks->Lsc[layer][pos]=coli_kvq_quant_row(Ls, coli_kv_row8(ks->Lc8[layer],pos,coli_kvq_row_bytes(c->kv_lora,g_tq_bits,g_tq_codec)), c->kv_lora, g_tq_bits, g_tq_codec);
+ ks->Rsc[layer][pos]=coli_kvq_quant_row(Rs, coli_kv_row8(ks->Rc8[layer],pos,coli_kvq_row_bytes(c->qk_rope,g_tq_bits,g_tq_codec)), c->qk_rope, g_tq_bits, g_tq_codec);
+ } else if(g_kv8){
+ /* KV8: norma+rope sul residuo di comp (scratch, mai riletto), poi
+ * quantizza riga+scala. E' IL produttore caldo: ogni token, ogni layer. */
+ float *Ls=comp+(int64_t)s*cw, *Rs=Ls+c->kv_lora;
+ rmsnorm(Ls, Ls, l->kv_a_ln, c->kv_lora, c->eps); /* latente normato */
+ rope_interleave(Rs, pos, c); /* k_rot roped */
+ ks->Lsc[layer][pos]=coli_kv8_quant_row(Ls, coli_kv_row8(ks->Lc8[layer],pos,c->kv_lora), c->kv_lora);
+ ks->Rsc[layer][pos]=coli_kv8_quant_row(Rs, coli_kv_row8(ks->Rc8[layer],pos,c->qk_rope), c->qk_rope);
+ } else {
+ float *Ldst=coli_kv_row(ks->Lc[layer],pos,c->kv_lora);
+ float *Rdst=coli_kv_row(ks->Rc[layer],pos,c->qk_rope);
+ memcpy(Ldst, cs, c->kv_lora*sizeof(float));
+ rmsnorm(Ldst, Ldst, l->kv_a_ln, c->kv_lora, c->eps); /* latente normato */
+ memcpy(Rdst, cs+c->kv_lora, c->qk_rope*sizeof(float));
+ rope_interleave(Rdst, pos, c); /* k_rot roped, condiviso fra teste */
+ }
}
}
/* ---- DSA lightning indexer ----
@@ -4206,8 +4250,19 @@ static void attention_rows(Model *m, Layer *l, int layer, float *x, int S, int p
}
int cuda_absorb=0;
#ifdef COLI_CUDA
+ /* QUANT GUARD (!g_kv8&&!g_tq): the CUDA absorb kernels read f32 Lc/Rc rows, which are
+ * not allocated under KV8/KV_TQ. Quantized KV takes the CPU consumer below (which decodes
+ * the byte cache natively); the fp8/int4 CUDA kernels are the follow-up PR. */
cuda_absorb=layer<c->n_layers&&!kvs&&g_cuda_enabled&&getenv("COLI_CUDA_ATTN")&&
- atoi(getenv("COLI_CUDA_ATTN"))&&c->kv_lora<=512;
+ atoi(getenv("COLI_CUDA_ATTN"))&&c->kv_lora<=512&&!g_kv8&&!g_tq;
+ /* Non-silent: say so ONCE so a CUDA operator isn't puzzled by CPU-bound attention. */
+ if((g_kv8||g_tq) && g_cuda_enabled && getenv("COLI_CUDA_ATTN") && atoi(getenv("COLI_CUDA_ATTN"))){
+ static int kvq_cuda_noted=0;
+ if(!kvq_cuda_noted){ kvq_cuda_noted=1;
+ fprintf(stderr,"[%s] no CUDA attention kernels for quantized KV yet: "
+ "attention uses the CPU consumer (native byte-cache decode). Follow-up PR.\n",
+ g_tq?"KV_TQ":"KV8"); }
+ }
#endif
int absorb = kvs || g_absorb==1 || (g_absorb<0 && S<=4) || cuda_absorb;
if(absorb && c->kv_lora<=512){
@@ -4230,7 +4285,11 @@ static void attention_rows(Model *m, Layer *l, int layer, float *x, int S, int p
float *sc_all = falloc((int64_t)omp_get_max_threads()*sc_cap);
int cuda_core=0,cuda_projected=0;
#ifdef COLI_CUDA
- if(kvs&&g_cuda_enabled&&getenv("COLI_CUDA_ATTN")&&atoi(getenv("COLI_CUDA_ATTN"))&&
+ /* Ragged batched attention (multi-slot serve) is f32-only: under KV8/KV_TQ the
+ * f32 rows this branch reads (kvs[s]->Lc/Rc) are not even allocated; quantized
+ * ragged rows take the CPU ragged path instead, which decodes the byte cache
+ * natively. A quantized ragged gather is follow-up-PR work. */
+ if(kvs&&!g_kv8&&!g_tq&&g_cuda_enabled&&getenv("COLI_CUDA_ATTN")&&atoi(getenv("COLI_CUDA_ATTN"))&&
!dnsel&&l->kv_b.cuda_eligible&&l->o.cuda_eligible&&
qt_cuda_upload(&l->kv_b)&&qt_cuda_upload(&l->o)){
const float **rl=malloc((size_t)S*sizeof(*rl)),**rr=malloc((size_t)S*sizeof(*rr));
@@ -4270,8 +4329,8 @@ static void attention_rows(Model *m, Layer *l, int layer, float *x, int S, int p
cuda_core=cuda_projected=coli_cuda_attention_project_batch(l->kv_b.cuda,l->o.cuda,out,Q,
coli_kv_row(m->Lc[layer],st0,kvl),coli_kv_row(m->Rc[layer],st0,c->qk_rope),
S,H,c->qk_nope,c->qk_rope,vh,kvl,nt,c->attn_scale);
- } else if(S<=4&&g_cuda_enabled&&getenv("COLI_CUDA_ATTN")&&atoi(getenv("COLI_CUDA_ATTN"))&&
- l->kv_b.cuda_eligible&&qt_cuda_upload(&l->kv_b)){
+ } else if(S<=4&&g_cuda_enabled&&!g_kv8&&!g_tq&&getenv("COLI_CUDA_ATTN")&&atoi(getenv("COLI_CUDA_ATTN"))&&
+ l->kv_b.cuda_eligible&&qt_cuda_upload(&l->kv_b)){ /* quant guard: absorb/kvdev read f32 Lc/Rc rows */
cuda_core=1;
for(int s=0;s<S&&cuda_core;s++){
KVState *ks=kvs?kvs[s]:m->kv;int pos=positions?positions[s]:pos_base+s;
@@ -4373,7 +4432,43 @@ static void attention_rows(Model *m, Layer *l, int layer, float *x, int S, int p
int ns = (dnsel && dnsel[s]>0) ? dnsel[s] : 0; /* DSA: lista top-k o range pieno */
const int *tlist = ns ? dsel+(int64_t)s*dtopk : NULL;
int nt = ns ? ns : pos+1-st0;
+ /* codec-1 rotated-int4: rotate the query ONCE per head (q.x_hat == rotate(q).c, the
+ * same orthogonality identity the Metal/CUDA native kernels use) and dot the packed
+ * nibbles directly — instead of f32-dequantizing every shared latent row per head
+ * (2H-redundant). std = radius/sqrt(n) rides Lsc/Rsc. codec-0 keeps the dequant path. */
+ int tq1 = (g_tq && g_tq_codec==1);
+ float qtl[512], qtr[512];
+ float invsnL = tq1 ? 1.f/sqrtf((float)kvl) : 0.f, invsnR = tq1 ? 1.f/sqrtf((float)c->qk_rope) : 0.f;
+ int lrb1=0, rrb1=0;
+ if(tq1){ coli_tq_rotate(qabs,qtl,kvl,COLI_TQ_SEED); coli_tq_rotate(qr,qtr,c->qk_rope,COLI_TQ_SEED);
+ lrb1=coli_q4_row_bytes(kvl); rrb1=coli_q4_row_bytes(c->qk_rope); }
for(int jj=0;jj<nt;jj++){ int t = tlist ? tlist[jj] : st0+jj;
+ float a=0;
+ if(tq1){
+ const uint8_t *Lt=coli_kv_row8(ks->Lc8[layer],t,lrb1);
+ const uint8_t *Rt=coli_kv_row8(ks->Rc8[layer],t,rrb1);
+ float al=0, ar=0;
+ for(int i=0;i<kvl;i++){ int cc=(Lt[i>>1]>>((i&1)*4))&0xF; al+=qtl[i]*coli_q4_lev[cc]; }
+ for(int d=0;d<c->qk_rope;d++){ int cc=(Rt[d>>1]>>((d&1)*4))&0xF; ar+=qtr[d]*coli_q4_lev[cc]; }
+ a = al*ks->Lsc[layer][t]*invsnL + ar*ks->Rsc[layer][t]*invsnR;
+ } else if(g_tq){
+ /* PolarQuant (codec 0): ricostruisci la riga latente + rope a f32, poi il
+ * dot diretto (il raggio e' gia' nel dequant, niente scala esterna). */
+ float Lf[512], Rf[512];
+ coli_kvq_dequant_row(coli_kv_row8(ks->Lc8[layer],t,coli_kvq_row_bytes(kvl,g_tq_bits,g_tq_codec)), ks->Lsc[layer][t], Lf, kvl, g_tq_bits, g_tq_codec);
+ coli_kvq_dequant_row(coli_kv_row8(ks->Rc8[layer],t,coli_kvq_row_bytes(c->qk_rope,g_tq_bits,g_tq_codec)), ks->Rsc[layer][t], Rf, c->qk_rope, g_tq_bits, g_tq_codec);
+ for(int i=0;i<kvl;i++) a+=qabs[i]*Lf[i];
+ for(int d=0;d<c->qk_rope;d++) a+=qr[d]*Rf[d];
+ } else if(g_kv8){
+ /* LUT-dequant inline nel dot; la scala per-riga esce dalla
+ * somma: score = Lsc·Σ q·lut[b] + Rsc·Σ qr·lut[b] */
+ const uint8_t *Lt=coli_kv_row8(ks->Lc8[layer],t,kvl);
+ const uint8_t *kr=coli_kv_row8(ks->Rc8[layer],t,c->qk_rope);
+ float al=0, ar=0;
+ for(int i=0;i<kvl;i++) al+=qabs[i]*coli_fp8_lut[Lt[i]];
+ for(int d=0;d<c->qk_rope;d++) ar+=qr[d]*coli_fp8_lut[kr[d]];
+ a=al*ks->Lsc[layer][t]+ar*ks->Rsc[layer][t];
+ } else {
const float *Lt=coli_kv_row(ks->Lc[layer],t,kvl);
const float *kr=coli_kv_row(ks->Rc[layer],t,c->qk_rope);
/* MLA-absorb score: dot(qabs, Lt) + dot(qr, kr). #442: the qabs·Lt
@@ -4382,7 +4477,7 @@ static void attention_rows(Model *m, Layer *l, int layer, float *x, int S, int p
* AVX2 (8-lane fmadd + hsum256, same shape as matmul_q in quant.h)
* and NEON, with a scalar tail for the remainder. Reassociation
* is accepted here — softmax downstream softens the rounding flip. */
- float a=0; int i=0;
+ int i=0;
#if defined(__AVX2__)
__m256 acc=_mm256_setzero_ps();
for(;i+8<=kvl;i+=8)
@@ -4397,11 +4492,28 @@ static void attention_rows(Model *m, Layer *l, int layer, float *x, int S, int p
#endif
for(;i<kvl;i++) a+=qabs[i]*Lt[i];
for(int d=0;d<c->qk_rope;d++) a+=qr[d]*kr[d];
+ }
sc[jj]=a*c->attn_scale;
}
softmax(sc,nt);
float clat[512]; memset(clat,0,kvl*sizeof(float));
for(int jj=0;jj<nt;jj++){ int t = tlist ? tlist[jj] : st0+jj;
+ if(tq1){
+ /* accumulate acc = sum_t w_t*std_t*lev[L[t]] in the rotated basis; unrotate
+ * ONCE after the loop (context = unrotate(sum_t w_t c_t)). */
+ const uint8_t *Lt=coli_kv_row8(ks->Lc8[layer],t,lrb1);
+ float a=sc[jj]*ks->Lsc[layer][t]*invsnL;
+ for(int i=0;i<kvl;i++){ int cc=(Lt[i>>1]>>((i&1)*4))&0xF; clat[i]+=a*coli_q4_lev[cc]; }
+ } else if(g_tq){
+ float Lf[512];
+ coli_kvq_dequant_row(coli_kv_row8(ks->Lc8[layer],t,coli_kvq_row_bytes(kvl,g_tq_bits,g_tq_codec)), ks->Lsc[layer][t], Lf, kvl, g_tq_bits, g_tq_codec);
+ float a=sc[jj]; /* raggio gia' nel dequant */
+ for(int i=0;i<kvl;i++) clat[i]+=a*Lf[i];
+ } else if(g_kv8){
+ const uint8_t *Lt=coli_kv_row8(ks->Lc8[layer],t,kvl);
+ float a=sc[jj]*ks->Lsc[layer][t]; /* la scala si fonde nel peso */
+ for(int i=0;i<kvl;i++) clat[i]+=a*coli_fp8_lut[Lt[i]];
+ } else {
const float *Lt=coli_kv_row(ks->Lc[layer],t,kvl);
/* MLA-absorb value mix: clat += sc[jj] * Lt (AXPY over kvl).
* #442: SIMD-ified — each lane writes back independently so there
@@ -4421,7 +4533,8 @@ static void attention_rows(Model *m, Layer *l, int layer, float *x, int S, int p
}
#endif
for(;i<kvl;i++) clat[i]+=a*Lt[i];
- }
+ } }
+ if(tq1) coli_tq_unrotate(clat,kvl,COLI_TQ_SEED); /* rotated basis -> latent */
qt_matvec_rows(&l->kv_b, rbase+r0v, vh, clat, ctx+((int64_t)s*H+h)*vh);
}
}
@@ -4455,8 +4568,11 @@ static void attention_rows(Model *m, Layer *l, int layer, float *x, int S, int p
int dsa_any=0; if(dnsel) for(int s=0;s<S && !dsa_any;s++) if(dnsel[s]>0) dsa_any=1;
int64_t kvb_rows=(int64_t)Tk-stL, kvb_need=kvb_rows*kvb_dim*4;
int64_t flash_mb=getenv("KVB_FLASH_MB")?atoll(getenv("KVB_FLASH_MB")):2048;
- int use_flash=!dsa_any && flash_mb>0 && kvb_need>flash_mb*1048576;
- if(getenv("KVB_FLASH")) use_flash=!dsa_any && atoi(getenv("KVB_FLASH"))!=0;
+ int kv_quant = g_kv8 || g_tq; /* KV8/KV_TQ read Lc via a dequant staging pass:
+ * they keep the one-shot path below for now (the
+ * flash/gather arms read f32 Lc rows directly). */
+ int use_flash=!dsa_any && !kv_quant && flash_mb>0 && kvb_need>flash_mb*1048576;
+ if(getenv("KVB_FLASH")) use_flash=!dsa_any && !kv_quant && atoi(getenv("KVB_FLASH"))!=0;
if(use_flash){
int64_t tile_mb=getenv("KVB_TILE_MB")?atoll(getenv("KVB_TILE_MB")):512;
int64_t tile=tile_mb*1048576/((int64_t)kvb_dim*4);
@@ -4529,7 +4645,7 @@ static void attention_rows(Model *m, Layer *l, int layer, float *x, int S, int p
* least halve the buffer, fall back to one-shot (gather overhead without the
* memory win). kvb_map: row t -> compact index, -1 = not rebuilt (never read). */
float *kvb_all=NULL; int32_t *kvb_map=NULL;
- if(dsa_any && flash_mb>0 && kvb_need>flash_mb*1048576){
+ if(dsa_any && !kv_quant && flash_mb>0 && kvb_need>flash_mb*1048576){
uint8_t *want=calloc((size_t)kvb_rows,1);
if(want){
for(int s=0;s<S;s++){
@@ -4567,7 +4683,26 @@ static void attention_rows(Model *m, Layer *l, int layer, float *x, int S, int p
}
if(!kvb_map){
kvb_all=falloc((int64_t)Tk*kvb_dim);
- matmul_qt(kvb_all+(int64_t)stL*kvb_dim, m->Lc[layer]+(int64_t)stL*c->kv_lora, &l->kv_b, Tk-stL);
+ if(g_tq){
+ /* PolarQuant: ricostruisci il latente a f32 (kv_b vuole righe float). */
+ float *Lf=falloc((int64_t)(Tk-stL)*c->kv_lora);
+ int lbb=coli_kvq_row_bytes(c->kv_lora,g_tq_bits,g_tq_codec);
+ for(int t=stL;t<Tk;t++)
+ coli_kvq_dequant_row(coli_kv_row8(m->Lc8[layer],t,lbb), m->Lsc[layer][t],
+ Lf+(int64_t)(t-stL)*c->kv_lora, c->kv_lora, g_tq_bits, g_tq_codec);
+ matmul_qt(kvb_all+(int64_t)stL*kvb_dim, Lf, &l->kv_b, Tk-stL);
+ free(Lf);
+ } else if(g_kv8){
+ /* staging f32 del latente dequantizzato: kv_b vuole righe float. Il buffer
+ * [Tk-stL,kvl] e' rumore rispetto a kvb_all [Tk,H*(nope+vh)] gia' allocato. */
+ float *Lf=falloc((int64_t)(Tk-stL)*c->kv_lora);
+ for(int t=stL;t<Tk;t++)
+ coli_kv8_dequant_row(coli_kv_row8(m->Lc8[layer],t,c->kv_lora), m->Lsc[layer][t],
+ Lf+(int64_t)(t-stL)*c->kv_lora, c->kv_lora);
+ matmul_qt(kvb_all+(int64_t)stL*kvb_dim, Lf, &l->kv_b, Tk-stL);
+ free(Lf);
+ } else
+ matmul_qt(kvb_all+(int64_t)stL*kvb_dim, m->Lc[layer]+(int64_t)stL*c->kv_lora, &l->kv_b, Tk-stL);
}
m->t_kvb += now_s()-tk0;
/* 3) attenzione causale: score = q_pass·k_nope + q_rot·k_rot
@@ -4589,9 +4724,19 @@ static void attention_rows(Model *m, Layer *l, int layer, float *x, int S, int p
for(int jj=0;jj<nt;jj++){ int t = tlist ? tlist[jj] : st0+jj;
int64_t ti = kvb_map ? (int64_t)kvb_map[t-stL] : (int64_t)t; /* gathered vs absolute row */
const float *kn=kvb_all+ti*kvb_dim+(int64_t)h*(c->qk_nope+vh);
- const float *kr=m->Rc[layer]+(int64_t)t*c->qk_rope;
float a=0; for(int d=0;d<c->qk_nope;d++) a+=qp[d]*kn[d];
- for(int d=0;d<c->qk_rope;d++) a+=qr[d]*kr[d];
+ if(g_tq){
+ float Rf[512];
+ coli_kvq_dequant_row(coli_kv_row8(m->Rc8[layer],t,coli_kvq_row_bytes(c->qk_rope,g_tq_bits,g_tq_codec)), m->Rsc[layer][t], Rf, c->qk_rope, g_tq_bits, g_tq_codec);
+ for(int d=0;d<c->qk_rope;d++) a+=qr[d]*Rf[d];
+ } else if(g_kv8){
+ const uint8_t *kr=coli_kv_row8(m->Rc8[layer],t,c->qk_rope);
+ float ar=0; for(int d=0;d<c->qk_rope;d++) ar+=qr[d]*coli_fp8_lut[kr[d]];
+ a+=ar*m->Rsc[layer][t];
+ } else {
+ const float *kr=m->Rc[layer]+(int64_t)t*c->qk_rope;
+ for(int d=0;d<c->qk_rope;d++) a+=qr[d]*kr[d];
+ }
sc[jj]=a*c->attn_scale;
}
softmax(sc,nt);
@@ -6450,6 +6595,8 @@ static void layer_forward_rows(Model *m, Layer *l, int li, float *x, int S, int
* Fallback: qualsiasi condizione mancante -> percorso CPU intero qui sotto.
* !kvs: ragged mux rows (per-row KV/position) are not expressible in this kernel's
* single Lc/Rc + pos_base contract — see the matching guard in attention_rows.
+ * QUANT GUARD (!g_kv8&&!g_tq): the fused layer kernel reads f32 Lc/Rc rows (not
+ * allocated under KV8/KV_TQ); quantized KV falls to the CPU path below.
* metal_fused_layer_fmt_miss & METAL_FUSED_LAYER_TENSORS: kv_b on its
* two-format+mode term (fmt==2, or fmt==4 with g_moe_exact off) plus the
* POSITIVE allowlist (fmt 1/2/3/4) over q_a/q_b/kv_a/o/sh_gate/sh_up/sh_down,
@@ -6465,7 +6612,7 @@ static void layer_forward_rows(Model *m, Layer *l, int li, float *x, int S, int
* matmul_qt_ex/matmul_fp8. Fixing WP_() and wiring fmt=8 through bind_gemv
* is the same deferred follow-up noted in attention_rows, not done in this
* round. */
- if(g_metal_enabled && !kvs && S<=4 && li<c->n_layers && l->sparse
+ if(g_metal_enabled && !kvs && !g_kv8 && !g_tq && S<=4 && li<c->n_layers && l->sparse
&& (g_absorb==1||(g_absorb<0&&S<=4)) && m->kv_start[li]==0
&& D==6144 && c->n_heads==64 && c->q_lora==2048 && c->kv_lora==512
&& c->qk_nope==192 && c->qk_rope==64 && c->v_head==256
@@ -6645,6 +6792,11 @@ static void kv_alloc(Model *m, int max_t){
if(g_metal_enabled){ coli_metal_unregister(k->Lc[i]); coli_metal_unregister(k->Rc[i]); }
#endif
free(k->Lc[i]); free(k->Rc[i]); } free(k->Lc); free(k->Rc); }
+ if(k->Lc8){ for(int i=0;i<c->n_layers+1;i++){
+ free(k->Lc8[i]); free(k->Rc8[i]);
+ free(k->Lsc[i]); free(k->Rsc[i]); }
+ free(k->Lc8); free(k->Rc8); free(k->Lsc); free(k->Rsc);
+ k->Lc8=k->Rc8=NULL; k->Lsc=k->Rsc=NULL; }
if(k->Ic){ for(int i=0;i<c->n_layers;i++) free(k->Ic[i]); free(k->Ic); k->Ic=NULL; }
if(m->has_dsa){
k->Ic=calloc(c->n_layers,sizeof(float*));
@@ -6653,6 +6805,23 @@ static void kv_alloc(Model *m, int max_t){
k->max_t=max_t;
int NR=c->n_layers+1; /* riga extra: KV del layer MTP */
k->Lc=calloc(NR,sizeof(float*)); k->Rc=calloc(NR,sizeof(float*));
+ if(g_kv8 || g_tq){
+ /* KV8: byte fp8 + una scala f32 per riga. KV_TQ: byte polari impacchettati +
+ * raggio f32 per riga. In entrambi i casi Lc/Rc restano NULL e le righe hanno
+ * larghezza in BYTE lb/rb — KV8: kv_lora/qk_rope (1 byte/valore); TQ:
+ * coli_tq_row_bytes (< kv_lora, solo gli angoli). Lsc/Rsc reggono scala|raggio. */
+ int lb = g_tq ? coli_kvq_row_bytes(c->kv_lora,g_tq_bits,g_tq_codec) : c->kv_lora;
+ int rb = g_tq ? coli_kvq_row_bytes(c->qk_rope,g_tq_bits,g_tq_codec) : c->qk_rope;
+ if(g_kv8) coli_fp8_lut_init();
+ k->Lc8=calloc(NR,sizeof(uint8_t*)); k->Rc8=calloc(NR,sizeof(uint8_t*));
+ k->Lsc=calloc(NR,sizeof(float*)); k->Rsc=calloc(NR,sizeof(float*));
+ for(int i=0;i<NR;i++){
+ k->Lc8[i]=malloc((size_t)max_t*lb);
+ k->Rc8[i]=malloc((size_t)max_t*rb);
+ k->Lsc[i]=falloc(max_t); k->Rsc[i]=falloc(max_t);
+ if(!k->Lc8[i]||!k->Rc8[i]){fprintf(stderr,"OOM kv8\n");exit(1);}
+ }
+ } else
for(int i=0;i<NR;i++){ k->Lc[i]=falloc((int64_t)max_t*c->kv_lora);
k->Rc[i]=falloc((int64_t)max_t*c->qk_rope);
#ifdef COLI_METAL
@@ -6669,6 +6838,7 @@ static void kv_alloc(Model *m, int max_t){
#endif
}
m->Lc=k->Lc; m->Rc=k->Rc; m->Ic=k->Ic; m->max_t=k->max_t; m->kv_start=k->kv_start;
+ m->Lc8=k->Lc8; m->Rc8=k->Rc8; m->Lsc=k->Lsc; m->Rsc=k->Rsc;
}
static void kv_bind(Model *m, KVState *k){
@@ -6679,6 +6849,7 @@ static void kv_bind(Model *m, KVState *k){
for(int i=0;i<m->c.n_layers+1;i++) m->vk_kv_valid[i]=0;
#endif
m->kv=k; m->Lc=k->Lc; m->Rc=k->Rc; m->Ic=k->Ic;
+ m->Lc8=k->Lc8; m->Rc8=k->Rc8; m->Lsc=k->Lsc; m->Rsc=k->Rsc;
m->max_t=k->max_t; m->kv_start=k->kv_start;
}
@@ -6749,7 +6920,10 @@ static float *step_decode_batch(Model *m, const DecodeRow *rows, int S){
free(x); return NULL;
}
for(int l=0;l<c->n_layers;l++){
- if(!rows[s].kv->Lc[l] || !rows[s].kv->Rc[l] ||
+ if(((g_kv8||g_tq) ? (!rows[s].kv->Lc8 || !rows[s].kv->Rc8 ||
+ !rows[s].kv->Lc8[l] || !rows[s].kv->Rc8[l] ||
+ !rows[s].kv->Lsc[l] || !rows[s].kv->Rsc[l])
+ : (!rows[s].kv->Lc[l] || !rows[s].kv->Rc[l])) ||
rows[s].kv->kv_start[l]<0 || rows[s].kv->kv_start[l]>rows[s].pos ||
(m->has_dsa && c->idx_type[l] &&
(!rows[s].kv->Ic || !rows[s].kv->Ic[l]))){ free(x); return NULL; }
@@ -7977,8 +8151,11 @@ static void serve_ctx_free(Model *m, ServeCtx *s){
if(k->disk_fp){ fclose(k->disk_fp); k->disk_fp=NULL; }
free(k->disk_buf); k->disk_buf=NULL;
if(k->Lc) for(int i=0;i<NR;i++){ free(k->Lc[i]); free(k->Rc[i]); }
+ if(k->Lc8) for(int i=0;i<NR;i++){ free(k->Lc8[i]); free(k->Rc8[i]);
+ free(k->Lsc[i]); free(k->Rsc[i]); }
if(k->Ic) for(int i=0;i<m->c.n_layers;i++) free(k->Ic[i]);
- free(k->Lc); free(k->Rc); free(k->Ic); free(k->kv_start); free(s->hist);
+ free(k->Lc); free(k->Rc); free(k->Lc8); free(k->Rc8); free(k->Lsc); free(k->Rsc);
+ free(k->Ic); free(k->kv_start); free(s->hist);
}
typedef struct {
@@ -8561,7 +8738,7 @@ static void run_serve_mux(Model *m, const char *snap){
usage_save(m);
for(int i=0;i<nctx;i++){ serve_ctx_free(m,&ctx[i]); grammar_teardown(&grd[i]); }
free(ctx); free(req); free(grd);
- m->kv=NULL; m->Lc=m->Rc=m->Ic=NULL; m->kv_start=NULL; m->max_t=0;
+ m->kv=NULL; m->Lc=m->Rc=m->Ic=NULL; m->Lc8=m->Rc8=NULL; m->Lsc=m->Rsc=NULL; m->kv_start=NULL; m->max_t=0;
}
static void run_serve(Model *m, const char *snap){
@@ -8743,7 +8920,7 @@ static void run_serve(Model *m, const char *snap){
#undef len
#undef first
for(int i=0;i<nctx;i++) serve_ctx_free(m,&ctx[i]);
- free(ctx); m->kv=NULL; m->Lc=m->Rc=m->Ic=NULL; m->kv_start=NULL; m->max_t=0;
+ free(ctx); m->kv=NULL; m->Lc=m->Rc=m->Ic=NULL; m->Lc8=m->Rc8=NULL; m->Lsc=m->Rsc=NULL; m->kv_start=NULL; m->max_t=0;
}
static int *read_arr(jval*o,const char*k,int*n){
@@ -9471,13 +9648,21 @@ static int kv_slot_count(void){
}
static double kv_pool_bytes(Model *m, int max_ctx){
- Cfg *c=&m->c; double one=(double)(c->n_layers+1)*max_ctx*(c->kv_lora+c->qk_rope)*4.0;
+ /* KV8: 1 byte/valore + 8 B di scale per token/layer, non 4 B/valore. E' questo
+ * conto che governa expert_avail e cap_for_ram: con KV8 il clamp PIN recupera
+ * ~35 GB/slot a 256k e KV_SLOTS=2 smette di demolire gli expert su disco. */
+ Cfg *c=&m->c;
+ double one=(double)(c->n_layers+1)*max_ctx*
+ (g_tq ? (double)(coli_kvq_row_bytes(c->kv_lora,g_tq_bits,g_tq_codec)+coli_kvq_row_bytes(c->qk_rope,g_tq_bits,g_tq_codec))+8.0
+ : g_kv8 ? (double)(c->kv_lora+c->qk_rope)+8.0
+ : (c->kv_lora+c->qk_rope)*4.0);
if(m->has_dsa) for(int i=0;i<c->n_layers;i++) if(c->idx_type[i])
one+=(double)max_ctx*c->index_hd*4.0;
int slots=kv_slot_count(); if(slots<1||slots>16) slots=1;
return one*slots;
}
+
/* byte disponibili per gli expert (pin + LRU) nel budget — specchio del conto di cap_for_ram */
static double expert_avail(Model *m, double ram_gb, int ebits, int max_ctx){
Cfg *c=&m->c; int64_t eb=expert_bytes_probe(m,ebits);
@@ -10489,6 +10674,37 @@ int main(int argc, char **argv){
int cap = coli_resolve_cap(cap_given, cap_arg, cap_env, g_ssd_fast, &cap_explicit);
if(g_ssd_fast && !cap_explicit)
fprintf(stderr,"METAL: fast SSD (%.1f GB/s) — page cache favored, expert cache minimal (cap 1); override with --cap\n", coli_ssd_gbs);
+ /* KV8=1: KV-cache latente in fp8 e4m3. CPU-only in questo PR: i percorsi CUDA/Metal
+ * che leggono righe f32 si spengono da soli (guardie), e COLI_CUDA_PIPE va disattivato
+ * (il pipe-prefill legge righe f32). I kernel nativi arrivano nei follow-up. */
+ g_kv8 = getenv("KV8")?atoi(getenv("KV8")):0;
+ if(g_kv8){
+#ifdef COLI_CUDA
+ if(g_cuda_pipe){
+ fprintf(stderr,"[KV8] COLI_CUDA_PIPE reads f32 KV rows; pipe disabled under KV8\n");
+ g_cuda_pipe=0;
+ }
+#endif
+ coli_fp8_lut_init();
+ fprintf(stderr,"[KV8] latent KV cache in fp8 e4m3 + per-row scale (~3.9x less KV RAM)\n");
+ }
+ /* KV_TQ=3|4: tier TurboQuant/PolarQuant (mutuamente esclusivo con KV8). CPU-only,
+ * come KV8: si spegne dove i percorsi leggono righe f32. */
+ { int tqv = getenv("KV_TQ")?atoi(getenv("KV_TQ")):0;
+ if(tqv){
+ if(g_kv8){ fprintf(stderr,"[KV_TQ] KV8 and KV_TQ are mutually exclusive; KV_TQ wins (KV8 off)\n"); g_kv8=0; }
+ if(tqv<2) tqv=2; if(tqv>6) tqv=6; /* documented 3|4; clamp to the header's grid range */
+ g_tq=1; g_tq_bits=tqv;
+ /* rotated int4 is a fixed 4-bit codec (best 4-bit for MLA); other bit widths and
+ * KV_TQ_POLAR=1 use PolarQuant (variable bits, paper-faithful). */
+ g_tq_codec = (getenv("KV_TQ_POLAR") || g_tq_bits!=4) ? 0 : 1;
+#ifdef COLI_CUDA
+ if(g_cuda_pipe){ fprintf(stderr,"[KV_TQ] COLI_CUDA_PIPE reads f32 KV rows; pipe disabled under KV_TQ\n"); g_cuda_pipe=0; }
+#endif
+ fprintf(stderr,"[KV_TQ] latent KV in %s (randomized-Hadamard rotation; radius = per-row scale)\n",
+ g_tq_codec ? "rotated int4 + Lloyd codebook (4-bit)" : "PolarQuant recursive-polar");
+ }
+ }
printf("== GLM C engine (glm_moe_dsa), cache=%d experts/layer | experts@%d-bit dense@%d-bit | idot: " IDOT_KERNEL " ==\n", cap, ebits, dbits);
g_mem_avail_boot = mem_available_gb();
#if !defined(_WIN32)
diff --git a/c/decode_batch.h b/c/decode_batch.h
index d81817d9..80222489 100644
--- a/c/decode_batch.h
+++ b/c/decode_batch.h
@@ -2,6 +2,7 @@
#define COLIBRI_DECODE_BATCH_H
#include <stddef.h>
+#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
@@ -17,6 +18,12 @@ static inline float *coli_kv_row(float *base, int position, int width)
* ceiling, adopted as the wire cap too (no named consumer asks for more). */
#define COLI_SUBMIT_TOPK_MAX 32
+/* KV8 twin: same row arithmetic on the fp8 (e4m3) byte cache. */
+static inline uint8_t *coli_kv_row8(uint8_t *base, int position, int width)
+{
+ return base + (size_t)position * (size_t)width;
+}
+
typedef struct {
unsigned long long id, bytes, gbytes;
int slot, max_tokens;
diff --git a/c/kv_fp8.h b/c/kv_fp8.h
new file mode 100644
index 00000000..480c601f
--- /dev/null
+++ b/c/kv_fp8.h
@@ -0,0 +1,67 @@
+#ifndef COLIBRI_KV_FP8_H
+#define COLIBRI_KV_FP8_H
+
+#include <stdint.h>
+#include <string.h>
+#include <math.h>
+
+/* FP8 e4m3 (OCP "fn" variant: no infinities, max ±448, NaN = S.1111.111) per la
+ * KV-cache latente MLA. Il latente compresso e' sia key sia value nell'attention
+ * assorbita, quindi l'errore di quantizzazione entra negli score E nel context —
+ * lo stesso regime della pratica FP8-KV di DeepSeek-V3. Scala per-riga (amax/448,
+ * f32, Lc e Rc separate): dentro una riga la dinamica e' piccola, tra token no.
+ * EN: e4m3 storage for the MLA latent KV rows, per-row f32 amax scale. Decode is
+ * lut[byte]*scale; encode is bit-math + round-to-nearest-even, no libraries. */
+
+static float coli_fp8_lut[256];
+
+static void coli_fp8_lut_init(void){
+ if(coli_fp8_lut[1]!=0.f) return; /* idempotente */
+ for(int b=0;b<256;b++){
+ int E=(b>>3)&0xF, M=b&7;
+ float v = E ? ldexpf(1.f+(float)M/8.f, E-7) /* normale: (1+M/8)*2^(E-7) */
+ : ldexpf((float)M, -9); /* denormale: M/8 * 2^-6 */
+ if(E==15 && M==7) v=0.f; /* codice NaN: mai scritto; inerte in lettura */
+ coli_fp8_lut[b] = (b&0x80) ? -v : v;
+ }
+}
+
+/* float -> e4m3, round-to-nearest-even, saturazione a ±448 (come __nv_cvt SATFINITE).
+ * NaN -> 0: una riga f32 con NaN avvelenerebbe comunque tutto; 0 e' inerte nei dot. */
+static inline uint8_t coli_fp8_enc(float f){
+ union { float f; uint32_t u; } v; v.f=f;
+ uint8_t s=(uint8_t)((v.u>>24)&0x80u);
+ float a=fabsf(f);
+ if(!(a<=448.f)) return (a!=a) ? 0 : (uint8_t)(s|0x7e); /* NaN -> 0, inf/overflow -> ±448 */
+ if(a<0x1p-6f){ /* griglia denormale: passo 2^-9 */
+ int k=(int)rintf(a*0x1p9f); /* RNE su [0..8] */
+ return (uint8_t)(s|(uint8_t)k); /* k==8 -> 0x08 = primo normale 2^-6 */
+ }
+ int e; frexpf(a,&e); /* a = m*2^e, m in [0.5,1) */
+ int E=e+6; /* esponente biased e4m3 (1..15) */
+ int k=(int)rintf(ldexpf(a,3-(e-1))); /* mantissa RNE in [8,16] */
+ if(k==16){ k=8; E++; } /* overflow di mantissa -> esponente su */
+ if(E>15||(E==15&&k>14)) return (uint8_t)(s|0x7e);
+ return (uint8_t)(s|(uint8_t)(E<<3)|(uint8_t)(k-8));
+}
+
+/* quantizza una riga latente: scala amax/448 per-riga, ritorna la scala.
+ * La riga si decodifica come coli_fp8_lut[b]*scale. Riga tutta zero, subnormale
+ * (448/amax andrebbe a +inf), tutta NaN o con ±inf: byte 0 e scala 1, niente 1/0.
+ * NB: un NaN MISTO a valori finiti non alza amax (fabsf(NaN)>amax e' falso) —
+ * la riga si quantizza normalmente e il NaN diventa byte 0 via coli_fp8_enc. */
+static inline float coli_kv8_quant_row(const float *src, uint8_t *dst, int n){
+ float amax=0;
+ for(int i=0;i<n;i++){ float a=fabsf(src[i]); if(a>amax) amax=a; }
+ if(!(amax>1e-35f) || amax>3.4e38f){ memset(dst,0,(size_t)n); return 1.f; }
+ float inv=448.f/amax;
+ for(int i=0;i<n;i++) dst[i]=coli_fp8_enc(src[i]*inv);
+ return amax/448.f;
+}
+
+/* dequantizza una riga (staging f32 per i consumatori matmul) */
+static inline void coli_kv8_dequant_row(const uint8_t *src, float scale, float *dst, int n){
+ for(int i=0;i<n;i++) dst[i]=coli_fp8_lut[src[i]]*scale;
+}
+
+#endif
diff --git a/c/kv_persist.h b/c/kv_persist.h
index 51289a89..65c25437 100644
--- a/c/kv_persist.h
+++ b/c/kv_persist.h
@@ -6,18 +6,24 @@
#define KV_PERSIST_H
static int g_kvsave=1;
-#define KV_MAGIC "COLIKV1\0"
+#define KV_MAGIC "COLIKV1\0" /* v1: righe Lc/Rc f32 */
+#define KV_MAGIC2 "COLIKV2\0" /* v2 (KV8): righe fp8 e4m3 + scala f32 per riga */
+#define KV_MAGIC3 "COLIKV3\0" /* v3 (KV_TQ): righe PolarQuant + raggio f32 per riga (h[7]=bits) */
+static const char *kv_active_magic(void){ return g_tq?KV_MAGIC3 : g_kv8?KV_MAGIC2 : KV_MAGIC; }
static void kv_hdr(Model *m, int32_t *h, int nrec){
Cfg *c=&m->c; int nic=0;
for(int i=0;i<c->n_layers;i++) if(m->Ic && m->Ic[i]) nic++;
h[0]=c->n_layers; h[1]=c->kv_lora; h[2]=c->qk_rope;
- h[3]=m->has_dsa?c->index_hd:0; h[4]=nic; h[5]=c->vocab; h[6]=nrec; h[7]=0;
+ h[3]=m->has_dsa?c->index_hd:0; h[4]=nic; h[5]=c->vocab; h[6]=nrec;
+ h[7]=g_tq?((g_tq_codec<<8)|g_tq_bits):(g_kv8?1:0); /* format tag: 0=f32, 1=kv8; TQ: codec<<8 | bit width */
}
static int64_t kv_rec_bytes(Model *m){
Cfg *c=&m->c;
- int64_t rec = 4 + (int64_t)c->n_layers*(c->kv_lora+c->qk_rope)*4;
+ int64_t rec = 4 + (g_tq ? (int64_t)c->n_layers*(coli_kvq_row_bytes(c->kv_lora,g_tq_bits,g_tq_codec)+coli_kvq_row_bytes(c->qk_rope,g_tq_bits,g_tq_codec)+8)
+ : g_kv8 ? (int64_t)c->n_layers*(c->kv_lora+c->qk_rope+8)
+ : (int64_t)c->n_layers*(c->kv_lora+c->qk_rope)*4);
if(m->has_dsa) for(int i=0;i<c->n_layers;i++) if(m->Ic[i]) rec+=(int64_t)c->index_hd*4;
return rec;
}
@@ -26,11 +32,15 @@ static int kv_disk_open(Model *m){
KVState *k=m->kv;
if(k->disk_fp) return 1;
k->disk_fp=fopen(k->disk_path,"r+b");
+ if(k->disk_fp){ char mg[8]; /* formato del file != formato attivo -> riscrivi */
+ if(fread(mg,1,8,k->disk_fp)!=8 || memcmp(mg,kv_active_magic(),8)){
+ fclose(k->disk_fp); k->disk_fp=NULL; k->disk_nrec=0; }
+ }
if(!k->disk_fp){
k->disk_fp=fopen(k->disk_path,"wb");
if(!k->disk_fp) return 0;
int32_t h[8]; kv_hdr(m,h,0);
- fwrite(KV_MAGIC,1,8,k->disk_fp); fwrite(h,4,8,k->disk_fp);
+ fwrite(kv_active_magic(),1,8,k->disk_fp); fwrite(h,4,8,k->disk_fp);
fflush(k->disk_fp);
fclose(k->disk_fp);
k->disk_fp=fopen(k->disk_path,"r+b");
@@ -42,6 +52,11 @@ static int kv_disk_open(Model *m){
static void kv_disk_truncate(Model *m, int nrec){
if(!g_kvsave) return;
KVState *k=m->kv;
+ /* Mai scrivere nell'header piu' record di quanti ne esistano fisicamente:
+ * un append saltato (OOM dello staging, open fallita) lascia disk_nrec<len,
+ * e un truncate al prefix comune dentro quel buco estenderebbe il file su
+ * record MAI scritti — il load successivo li leggerebbe come spazzatura. */
+ if(nrec>k->disk_nrec) nrec=k->disk_nrec;
if(k->disk_fp){ fclose(k->disk_fp); k->disk_fp=NULL; }
FILE *f=fopen(k->disk_path,"r+b");
if(!f){ k->disk_nrec=0; return; }
@@ -69,19 +84,53 @@ static void kv_disk_append(Model *m, const int *hist, int len){
uint8_t *b=k->disk_buf;
*(int32_t*)b = hist[p]; b+=4;
for(int i=0;i<c->n_layers;i++){
- memcpy(b, m->Lc[i]+(int64_t)p*c->kv_lora, (size_t)c->kv_lora*4); b+=c->kv_lora*4;
- memcpy(b, m->Rc[i]+(int64_t)p*c->qk_rope,(size_t)c->qk_rope*4); b+=c->qk_rope*4;
+ if(g_tq){ /* v3: byte polari (righe strette) + raggio per riga */
+ int lbb=coli_kvq_row_bytes(c->kv_lora,g_tq_bits,g_tq_codec), rbb=coli_kvq_row_bytes(c->qk_rope,g_tq_bits,g_tq_codec);
+ memcpy(b, coli_kv_row8(m->Lc8[i],p,lbb), (size_t)lbb); b+=lbb;
+ memcpy(b, &m->Lsc[i][p], 4); b+=4;
+ memcpy(b, coli_kv_row8(m->Rc8[i],p,rbb), (size_t)rbb); b+=rbb;
+ memcpy(b, &m->Rsc[i][p], 4); b+=4;
+ } else if(g_kv8){ /* v2: fp8 + scala per riga, stesso staging */
+ memcpy(b, coli_kv_row8(m->Lc8[i],p,c->kv_lora), (size_t)c->kv_lora); b+=c->kv_lora;
+ memcpy(b, &m->Lsc[i][p], 4); b+=4;
+ memcpy(b, coli_kv_row8(m->Rc8[i],p,c->qk_rope), (size_t)c->qk_rope); b+=c->qk_rope;
+ memcpy(b, &m->Rsc[i][p], 4); b+=4;
+ } else {
+ memcpy(b, m->Lc[i]+(int64_t)p*c->kv_lora, (size_t)c->kv_lora*4); b+=c->kv_lora*4;
+ memcpy(b, m->Rc[i]+(int64_t)p*c->qk_rope,(size_t)c->qk_rope*4); b+=c->qk_rope*4;
+ }
}
if(m->has_dsa) for(int i=0;i<c->n_layers;i++) if(m->Ic[i]){
memcpy(b, m->Ic[i]+(int64_t)p*c->index_hd, (size_t)c->index_hd*4); b+=c->index_hd*4;
}
fwrite(k->disk_buf, 1, (size_t)rec, f);
}
- fflush(f);
+ fflush(f); /* dati prima, contatore poi */
+#ifdef _WIN32
+ _commit(_fileno(f));
+#else
+ fsync(fileno(f)); /* i DATI su disco prima che il contatore li
+ * dichiari: fflush ferma solo alla page cache */
+#endif
int32_t nr=len; fseek(f,8+6*4,SEEK_SET); fwrite(&nr,4,1,f);
- fflush(f);
+ fflush(f); /* persist the counter too */
+#ifdef _WIN32
+ _commit(_fileno(f));
+#else
+ fsync(fileno(f));
+#endif
k->disk_nrec=len;
}
+/* Bonifica una riga fp8 letta da disco: l'encoder non emette MAI i codici NaN e4m3
+ * (0x7F/0xFF), ma un file corrotto potrebbe — la GPU (__nv_cvt) li decodifica NaN. */
+static inline void kv8_sanitize_row(uint8_t *b, int n, float *sc){
+ if(!(fabsf(*sc)<3.4e38f)){ memset(b,0,(size_t)n); *sc=1.f; return; }
+ for(int i=0;i<n;i++) if((b[i]&0x7F)==0x7F) b[i]=0;
+}
+/* v3: raggio non finito o negativo -> riga inerte (coli_kvq_dequant_row rende zero). */
+static inline void kv_tq_sanitize(float *radius){
+ if(!(*radius>=0.f && *radius<3.4e38f)) *radius=0.f;
+}
static int kv_disk_load(Model *m, int *hist, int maxctx){
if(!g_kvsave) return 0;
@@ -89,30 +138,80 @@ static int kv_disk_load(Model *m, int *hist, int maxctx){
Cfg *c=&m->c;
FILE *f=fopen(k->disk_path,"rb"); if(!f) return 0;
char mg[8]; int32_t h[8], w[8]; kv_hdr(m,w,0);
- if(fread(mg,1,8,f)!=8 || memcmp(mg,KV_MAGIC,8) || fread(h,4,8,f)!=8 ||
+ int dt=-1; /* dtype del FILE: 0=f32 (v1), 1=fp8 (v2), 2=PolarQuant (v3) */
+ if(fread(mg,1,8,f)==8){
+ if(!memcmp(mg,KV_MAGIC,8)) dt=0; else if(!memcmp(mg,KV_MAGIC2,8)) dt=1;
+ else if(!memcmp(mg,KV_MAGIC3,8)) dt=2; }
+ if(dt<0 || fread(h,4,8,f)!=8 ||
h[0]!=w[0]||h[1]!=w[1]||h[2]!=w[2]||h[3]!=w[3]||h[4]!=w[4]||h[5]!=w[5]){
fprintf(stderr,"[KV] ignoring .coli_kv from a different model or version\n"); fclose(f); return 0; }
+ if(dt==1 && !g_kv8){
+ fprintf(stderr,"[KV] .coli_kv is fp8 (saved under KV8=1): starting over (set KV8=1 to resume it)\n");
+ fclose(f); return 0; }
+ if(dt==2 && !g_tq){
+ fprintf(stderr,"[KV] .coli_kv is PolarQuant (saved under KV_TQ): starting over (set KV_TQ to resume it)\n");
+ fclose(f); return 0; }
+ if(dt==2 && g_tq && h[7]!=((g_tq_codec<<8)|g_tq_bits)){ /* h[7] = codec<<8 | bit width */
+ fprintf(stderr,"[KV] .coli_kv KV_TQ (codec %d, %d-bit) != current (codec %d, %d-bit): starting over\n",
+ (h[7]>>8)&0xFF, h[7]&0xFF, g_tq_codec, g_tq_bits);
+ fclose(f); return 0; }
int nrec=h[6];
if(nrec<1){ fclose(f); return 0; }
if(nrec>=maxctx-8-g_draft){
fprintf(stderr,"[KV] saved conversation (%d tokens) exceeds the context: starting over\n",nrec);
fclose(f); return 0; }
double t0=now_s();
+ /* v1 f32 sotto KV8/KV_TQ: righe f32 lette in staging e quantizzate al volo */
+ float *stage = ((g_kv8||g_tq)&&dt==0) ? falloc(c->kv_lora>c->qk_rope?c->kv_lora:c->qk_rope) : NULL;
for(int p=0;p<nrec;p++){
int32_t tk; if(fread(&tk,4,1,f)!=1){ nrec=p; break; } hist[p]=tk;
for(int i=0;i<c->n_layers;i++){
- if(fread(m->Lc[i]+(int64_t)p*c->kv_lora, 4, c->kv_lora, f)!=(size_t)c->kv_lora ||
- fread(m->Rc[i]+(int64_t)p*c->qk_rope, 4, c->qk_rope, f)!=(size_t)c->qk_rope){ nrec=p; goto out; }
+ if(dt==2){ /* v3: byte polari + raggio, gia' nel formato in RAM */
+ int lbb=coli_kvq_row_bytes(c->kv_lora,g_tq_bits,g_tq_codec), rbb=coli_kvq_row_bytes(c->qk_rope,g_tq_bits,g_tq_codec);
+ if(fread(coli_kv_row8(m->Lc8[i],p,lbb), 1, lbb, f)!=(size_t)lbb ||
+ fread(&m->Lsc[i][p], 4, 1, f)!=1 ||
+ fread(coli_kv_row8(m->Rc8[i],p,rbb), 1, rbb, f)!=(size_t)rbb ||
+ fread(&m->Rsc[i][p], 4, 1, f)!=1){ nrec=p; goto out; }
+ kv_tq_sanitize(&m->Lsc[i][p]); kv_tq_sanitize(&m->Rsc[i][p]);
+ } else if(dt==1){ /* v2: fp8+scala, gia' nel formato in RAM */
+ if(fread(coli_kv_row8(m->Lc8[i],p,c->kv_lora), 1, c->kv_lora, f)!=(size_t)c->kv_lora ||
+ fread(&m->Lsc[i][p], 4, 1, f)!=1 ||
+ fread(coli_kv_row8(m->Rc8[i],p,c->qk_rope), 1, c->qk_rope, f)!=(size_t)c->qk_rope ||
+ fread(&m->Rsc[i][p], 4, 1, f)!=1){ nrec=p; goto out; }
+ kv8_sanitize_row(coli_kv_row8(m->Lc8[i],p,c->kv_lora), c->kv_lora, &m->Lsc[i][p]);
+ kv8_sanitize_row(coli_kv_row8(m->Rc8[i],p,c->qk_rope), c->qk_rope, &m->Rsc[i][p]);
+ } else if(g_tq){ /* v1 f32 sotto KV_TQ: PolarQuant al volo */
+ if(fread(stage, 4, c->kv_lora, f)!=(size_t)c->kv_lora){ nrec=p; goto out; }
+ m->Lsc[i][p]=coli_kvq_quant_row(stage, coli_kv_row8(m->Lc8[i],p,coli_kvq_row_bytes(c->kv_lora,g_tq_bits,g_tq_codec)), c->kv_lora, g_tq_bits, g_tq_codec);
+ if(fread(stage, 4, c->qk_rope, f)!=(size_t)c->qk_rope){ nrec=p; goto out; }
+ m->Rsc[i][p]=coli_kvq_quant_row(stage, coli_kv_row8(m->Rc8[i],p,coli_kvq_row_bytes(c->qk_rope,g_tq_bits,g_tq_codec)), c->qk_rope, g_tq_bits, g_tq_codec);
+ } else if(g_kv8){ /* v1 f32 sotto KV8: fp8 al volo */
+ if(fread(stage, 4, c->kv_lora, f)!=(size_t)c->kv_lora){ nrec=p; goto out; }
+ m->Lsc[i][p]=coli_kv8_quant_row(stage, coli_kv_row8(m->Lc8[i],p,c->kv_lora), c->kv_lora);
+ if(fread(stage, 4, c->qk_rope, f)!=(size_t)c->qk_rope){ nrec=p; goto out; }
+ m->Rsc[i][p]=coli_kv8_quant_row(stage, coli_kv_row8(m->Rc8[i],p,c->qk_rope), c->qk_rope);
+ } else {
+ if(fread(m->Lc[i]+(int64_t)p*c->kv_lora, 4, c->kv_lora, f)!=(size_t)c->kv_lora ||
+ fread(m->Rc[i]+(int64_t)p*c->qk_rope, 4, c->qk_rope, f)!=(size_t)c->qk_rope){ nrec=p; goto out; }
+ }
}
if(m->has_dsa) for(int i=0;i<c->n_layers;i++) if(m->Ic[i])
if(fread(m->Ic[i]+(int64_t)p*c->index_hd, 4, c->index_hd, f)!=(size_t)c->index_hd){ nrec=p; goto out; }
}
out:
- fclose(f);
+ fclose(f); free(stage);
if(nrec>0){
if(m->has_mtp) m->kv_start[c->n_layers]=-1;
fprintf(stderr,"[KV] resumed conversation from disk: %d tokens in %.1fs (no re-prefill)\n",
nrec, now_s()-t0);
+ if((g_kv8||g_tq) && dt==0){
+ /* upgrade v1->v2/v3: il file f32 non puo' ricevere append quantizzati.
+ * disk_nrec=0 e il file resta INTATTO: al primo append il magic lo riscrive. */
+ k->disk_nrec=0;
+ fprintf(stderr,"[KV] f32 .coli_kv quantized in RAM; will be rewritten as %s at next save\n",
+ g_tq?"PolarQuant (v3)":"fp8 (v2)");
+ return nrec;
+ }
}
k->disk_nrec=nrec;
return nrec;
diff --git a/c/kv_tq.h b/c/kv_tq.h
new file mode 100644
index 00000000..178b763d
--- /dev/null
+++ b/c/kv_tq.h
@@ -0,0 +1,261 @@
+#ifndef COLIBRI_KV_TQ_H
+#define COLIBRI_KV_TQ_H
+
+#include <stdint.h>
+#include <string.h>
+#include <math.h>
+
+/* PolarQuant (Han/Kacham/Mirrokni/Zandieh/Karbasi, arXiv:2502.02617 — la base di
+ * TurboQuant): quantizzazione KV data-oblivious in due parti, senza calibrazione.
+ * 1) precondizionamento con una ROTAZIONE casuale (qui Hadamard randomizzato:
+ * sign-flip deterministico D + FWHT normalizzato H, ortonormale e auto-inverso)
+ * — rende le coordinate ~gaussiane, quindi la griglia degli angoli e' nota a
+ * priori e non serve normalizzare per riga;
+ * 2) TRASFORMATA POLARE ricorsiva a coppie: il vettore ruotato diventa (raggio,
+ * n-1 angoli). Il raggio E' la norma L2 della riga (la rotazione la conserva),
+ * quindi riusa la scala f32 per-riga che KV8 ha gia' (Lsc/Rsc). Solo gli angoli
+ * finiscono nei byte: livello 1 uniforme su (-pi,pi], livelli >=2 concentrati
+ * su pi/4 (griglia centrata, mezza-ampiezza analitica).
+ *
+ * EN: two-part data-oblivious KV quantization, no calibration. (1) randomized
+ * Hadamard rotation (deterministic sign flips + normalized self-inverse FWHT) makes
+ * coordinates near-Gaussian so the angle grid is distribution-free; (2) recursive
+ * pairwise polar transform turns the rotated row into (radius, n-1 angles). The
+ * radius is the row's L2 norm (rotation-invariant) and reuses the per-row f32 scale
+ * that KV8 already stores; only the angles are packed into bytes. Phase 1 is
+ * PolarQuant only — the QJL 1-bit residual (arXiv:2406.03482) is a later phase.
+ *
+ * n MUST be a power of two (kv_lora=512, qk_rope=64 both qualify) and <= COLI_TQ_MAXN.
+ * Decode is coli_tq_dequant_row -> f32 staging, same shape as coli_kv8_dequant_row. */
+
+#ifndef COLI_TQ_SEED
+#define COLI_TQ_SEED 0x9E3779B9u /* fixed rotation seed (golden ratio) */
+#endif
+#define COLI_TQ_MAXN 2048 /* max row width (kv_lora/qk_rope <= this) */
+
+/* ---- randomized Hadamard rotation ---------------------------------------- */
+
+/* splitmix32: deterministic bit-mix, gives the reproducible +-1 sign vector D. */
+static inline uint32_t coli_tq_hash(uint32_t x){
+ x += 0x9E3779B9u;
+ x = (x ^ (x>>16)) * 0x85EBCA6Bu;
+ x = (x ^ (x>>13)) * 0xC2B2AE35u;
+ return x ^ (x>>16);
+}
+static inline float coli_tq_sign(int i, uint32_t seed){
+ return (coli_tq_hash(seed ^ (uint32_t)i) & 1u) ? -1.f : 1.f;
+}
+
+/* Normalized fast Walsh-Hadamard transform, in place. H_n has +-1 entries and
+ * H_n^2 = n*I, so the normalized H/sqrt(n) is symmetric, orthogonal AND its own
+ * inverse: applying this twice returns the input (the "FWHT self-inverse" gate). */
+static inline void coli_tq_fwht(float *a, int n){
+ for(int len=1; len<n; len<<=1)
+ for(int i=0;i<n;i+=len<<1)
+ for(int j=i;j<i+len;j++){
+ float u=a[j], v=a[j+len];
+ a[j]=u+v; a[j+len]=u-v;
+ }
+ float inv=1.f/sqrtf((float)n);
+ for(int i=0;i<n;i++) a[i]*=inv;
+}
+
+/* y = R x = H (D x). R is orthonormal, so ||y|| == ||x||. */
+static inline void coli_tq_rotate(const float *x, float *y, int n, uint32_t seed){
+ for(int i=0;i<n;i++) y[i]=x[i]*coli_tq_sign(i,seed);
+ coli_tq_fwht(y,n);
+}
+/* x = R^-1 y = D (H y), in place (H symmetric orthogonal, D^-1 = D). */
+static inline void coli_tq_unrotate(float *y, int n, uint32_t seed){
+ coli_tq_fwht(y,n);
+ for(int i=0;i<n;i++) y[i]*=coli_tq_sign(i,seed);
+}
+
+/* ---- angle grids --------------------------------------------------------- */
+/* Bit split: level-1 angles (n/2 of them) get b1=bits; every deeper level gets
+ * b2=bits-1 (>=1). Level-1 angles are uniform on (-pi,pi] after the rotation;
+ * deeper-level angles are atan2 of two nonnegative sub-radii, in [0,pi/2] and
+ * sharply concentrated at pi/4 (variance ~ 1/(4s), s = subtree half-size), so a
+ * uniform grid would waste codes — we center a narrow uniform grid on pi/4. */
+static inline int coli_tq_b1(int bits){ return bits; }
+static inline int coli_tq_b2(int bits){ return bits>1 ? bits-1 : 1; }
+
+#ifndef COLI_TQ_PI
+#define COLI_TQ_PI 3.14159265358979323846f
+#endif
+
+/* level-1: uniform bins over (-pi,pi] */
+static inline uint32_t coli_tq_enc1(float ang, int b){
+ float u = (ang + COLI_TQ_PI) * (0.5f/COLI_TQ_PI); /* -> [0,1) */
+ int m = (1<<b)-1;
+ int q = (int)floorf(u*(float)(1<<b));
+ if(q<0) q=0; if(q>m) q=m;
+ return (uint32_t)q;
+}
+static inline float coli_tq_dec1(uint32_t q, int b){
+ return -COLI_TQ_PI + ((float)q+0.5f)*(2.f*COLI_TQ_PI)/(float)(1<<b);
+}
+
+/* deeper levels: half-width of the grid centered on pi/4. level>=2, s=2^(level-1);
+ * ~3 std = 3/(2*sqrt(s)), capped at pi/4 so the window stays inside [0,pi/2]. */
+static inline float coli_tq_hw(int level){
+ float s = (float)(1u << (level-1));
+ float w = 1.5f/sqrtf(s);
+ float cap = 0.25f*COLI_TQ_PI;
+ return w<cap ? w : cap;
+}
+static inline uint32_t coli_tq_enc2(float ang, int b, int level){
+ float w = coli_tq_hw(level);
+ float lo = 0.25f*COLI_TQ_PI - w; /* window [lo, lo+2w] */
+ float u = (ang - lo) / (2.f*w);
+ int m = (1<<b)-1;
+ int q = (int)floorf(u*(float)(1<<b));
+ if(q<0) q=0; if(q>m) q=m;
+ return (uint32_t)q;
+}
+static inline float coli_tq_dec2(uint32_t q, int b, int level){
+ float w = coli_tq_hw(level);
+ float lo = 0.25f*COLI_TQ_PI - w;
+ return lo + ((float)q+0.5f)*(2.f*w)/(float)(1<<b);
+}
+
+/* ---- bit-cursor packing (codes are <=6 bits, so a uint32 accumulator is ample) */
+static inline void coli_tq_wbits(uint8_t *buf, int *pos, uint32_t val, int w){
+ for(int k=0;k<w;k++){
+ int bit=(*pos)+k;
+ if((val>>k)&1u) buf[bit>>3] |= (uint8_t)(1u<<(bit&7));
+ }
+ *pos += w;
+}
+static inline uint32_t coli_tq_rbits(const uint8_t *buf, int *pos, int w){
+ uint32_t v=0;
+ for(int k=0;k<w;k++){
+ int bit=(*pos)+k;
+ if((buf[bit>>3]>>(bit&7))&1u) v |= (1u<<k);
+ }
+ *pos += w;
+ return v;
+}
+
+/* Packed byte count for one row: (n/2) level-1 angles + (n/2 - 1) deeper angles. */
+static inline int coli_tq_row_bytes(int n, int bits){
+ long total = (long)(n/2)*coli_tq_b1(bits) + (long)(n/2 - 1)*coli_tq_b2(bits);
+ return (int)((total + 7) / 8);
+}
+
+/* ---- encode / decode ----------------------------------------------------- */
+
+/* Quantize one latent row. Returns the radius (row L2 norm) to store in the
+ * per-row scale slot; packs the n-1 quantized angles into dst (dst must hold
+ * coli_tq_row_bytes(n,bits) bytes). A zero / subnormal / non-finite row is inert:
+ * radius 0, all-zero codes, and coli_tq_dequant_row reproduces the zero vector.
+ * (norm NaN/Inf both fail the finite guard, so a poisoned row never reaches FWHT.) */
+static inline float coli_tq_quant_row(const float *src, uint8_t *dst, int n, int bits){
+ int rb = coli_tq_row_bytes(n,bits);
+ memset(dst,0,(size_t)rb);
+ if(n<2 || n>COLI_TQ_MAXN || (n&(n-1))) return 0.f; /* n must be a power of two */
+
+ double ss=0; for(int i=0;i<n;i++) ss += (double)src[i]*(double)src[i];
+ float norm = (float)sqrt(ss);
+ if(!(norm>1e-35f) || norm>3.4e38f) return 0.f; /* zero / NaN / Inf -> inert */
+
+ float r[COLI_TQ_MAXN];
+ coli_tq_rotate(src, r, n, COLI_TQ_SEED); /* r starts as the rotated row */
+
+ int b1=coli_tq_b1(bits), b2=coli_tq_b2(bits), pos=0;
+ /* Reduce radii pair-by-pair, one level at a time; write each level's angles.
+ * r[j] is overwritten with the parent radius after its pair is consumed —
+ * safe because index j (<= the pair it reads) is never read again this level. */
+ for(int level=1, rlen=n; rlen>1; level++){
+ int half=rlen/2, b=(level==1)?b1:b2;
+ for(int j=0;j<half;j++){
+ float a=r[2*j], c=r[2*j+1];
+ float ang = atan2f(c,a);
+ uint32_t code = (level==1) ? coli_tq_enc1(ang,b) : coli_tq_enc2(ang,b,level);
+ coli_tq_wbits(dst,&pos,code,b);
+ r[j] = hypotf(a,c);
+ }
+ rlen=half;
+ }
+ return norm;
+}
+
+/* Reconstruct one row from its packed angles + radius (the stored scale). Inverse
+ * of coli_tq_quant_row: dequantize angles, rebuild the rotated vector top-down
+ * through the polar tree (each split preserves the parent radius exactly), then
+ * apply R^-1. radius<=0 or non-finite -> the zero vector. */
+static inline void coli_tq_dequant_row(const uint8_t *src, float radius, float *dst, int n, int bits){
+ if(n<2 || n>COLI_TQ_MAXN || (n&(n-1))){ memset(dst,0,(size_t)(n>0?n:0)*sizeof(float)); return; } /* power-of-two only */
+ if(!(radius>0.f) || radius>3.4e38f){ for(int i=0;i<n;i++) dst[i]=0.f; return; }
+
+ int b1=coli_tq_b1(bits), b2=coli_tq_b2(bits), pos=0;
+ /* Read angles in the SAME order they were written (level 1 first), dequantizing
+ * into a per-level-offset flat array. Level l has n/2^l angles at offset
+ * off[l] = n - n/2^(l-1); total n-1 entries. */
+ float ang[COLI_TQ_MAXN];
+ for(int level=1, len=n/2, off=0; len>=1; level++){
+ int b=(level==1)?b1:b2;
+ for(int j=0;j<len;j++){
+ uint32_t code = coli_tq_rbits(src,&pos,b);
+ ang[off+j] = (level==1) ? coli_tq_dec1(code,b) : coli_tq_dec2(code,b,level);
+ }
+ off += len;
+ if(len==1) break;
+ len >>= 1;
+ }
+
+ /* Rebuild top-down. cur holds r^(l) (clen radii); its angles are the level with
+ * exactly clen entries, which starts at offset n-2*clen (level l, clen=n/2^l ->
+ * off = n - n/2^(l-1) = n - 2*clen). Each split preserves the parent radius
+ * (cos^2+sin^2=1), so ||cur|| stays == radius all the way down to y (clen==n). */
+ float cur[COLI_TQ_MAXN], nxt[COLI_TQ_MAXN];
+ cur[0]=radius;
+ for(int clen=1; clen<n; clen*=2){
+ int off = n - 2*clen;
+ for(int j=0;j<clen;j++){
+ float aa = ang[off+j];
+ nxt[2*j] = cur[j]*cosf(aa);
+ nxt[2*j+1] = cur[j]*sinf(aa);
+ }
+ memcpy(cur,nxt,(size_t)(2*clen)*sizeof(float));
+ }
+ memcpy(dst,cur,(size_t)n*sizeof(float));
+ coli_tq_unrotate(dst,n,COLI_TQ_SEED);
+}
+
+/* ---- rotated int4 codec (codec 1, the competitive 4-bit tier) ---------------
+ * Same randomized-Hadamard rotation as PolarQuant, but the gaussianized coordinates are
+ * quantized with a fixed 16-level Lloyd-Max codebook (data-oblivious: N(0,1)-optimal, scaled
+ * per row by std = ||x||/sqrt(n)). Full reconstruction of the row, so it fixes BOTH the MLA
+ * key and the value (QJL residual only corrects scores) — ~0.10 rel L2 at 4 bit vs polar's
+ * ~0.15. Radius (row L2 norm) rides the per-row scale slot; 2 nibbles/byte, n even. */
+static const float coli_q4_lev[16]={ -2.733f,-2.069f,-1.618f,-1.256f,-0.942f,-0.657f,-0.388f,-0.128f,
+ 0.128f, 0.388f, 0.657f, 0.942f, 1.256f, 1.618f, 2.069f, 2.733f };
+static inline int coli_q4_row_bytes(int n){ return n/2; }
+static inline int coli_q4_enc(float v){ int best=0; float bd=1e30f;
+ for(int k=0;k<16;k++){ float d=fabsf(v-coli_q4_lev[k]); if(d<bd){bd=d;best=k;} } return best; }
+static inline float coli_q4_quant_row(const float *src, uint8_t *dst, int n){
+ int rb=coli_q4_row_bytes(n); memset(dst,0,(size_t)rb);
+ if(n<2 || n>COLI_TQ_MAXN || (n&(n-1))) return 0.f;
+ double ss=0; for(int i=0;i<n;i++) ss+=(double)src[i]*(double)src[i];
+ float norm=(float)sqrt(ss);
+ if(!(norm>1e-35f) || norm>3.4e38f) return 0.f; /* zero / NaN / Inf -> inert */
+ float y[COLI_TQ_MAXN]; coli_tq_rotate(src,y,n,COLI_TQ_SEED);
+ float invstd=sqrtf((float)n)/norm; /* y*invstd ~ N(0,1) */
+ for(int i=0;i<n;i++){ int c=coli_q4_enc(y[i]*invstd); dst[i>>1]|=(uint8_t)(c<<((i&1)*4)); }
+ return norm;
+}
+static inline void coli_q4_dequant_row(const uint8_t *src, float radius, float *dst, int n){
+ if(n<2 || n>COLI_TQ_MAXN || (n&(n-1))){ memset(dst,0,(size_t)(n>0?n:0)*sizeof(float)); return; }
+ if(!(radius>0.f) || radius>3.4e38f){ for(int i=0;i<n;i++) dst[i]=0.f; return; }
+ float std=radius/sqrtf((float)n);
+ for(int i=0;i<n;i++){ int c=(src[i>>1]>>((i&1)*4))&0xF; dst[i]=coli_q4_lev[c]*std; }
+ coli_tq_unrotate(dst,n,COLI_TQ_SEED);
+}
+
+/* ---- codec dispatch: 0 = PolarQuant (paper-faithful, variable bits), 1 = rotated int4 ---- */
+static inline int coli_kvq_row_bytes(int n,int bits,int codec){ return codec? coli_q4_row_bytes(n) : coli_tq_row_bytes(n,bits); }
+static inline float coli_kvq_quant_row(const float*s,uint8_t*d,int n,int bits,int codec){ return codec? coli_q4_quant_row(s,d,n) : coli_tq_quant_row(s,d,n,bits); }
+static inline void coli_kvq_dequant_row(const uint8_t*s,float sc,float*d,int n,int bits,int codec){ if(codec) coli_q4_dequant_row(s,sc,d,n); else coli_tq_dequant_row(s,sc,d,n,bits); }
+
+#endif
diff --git a/c/tests/test_kv_alloc.c b/c/tests/test_kv_alloc.c
index d080c08c..06336335 100644
--- a/c/tests/test_kv_alloc.c
+++ b/c/tests/test_kv_alloc.c
@@ -18,6 +18,26 @@ int main(void){
m.Lc[i][(int64_t)32*m.c.kv_lora-1]=2.0f;
m.Rc[i][(int64_t)32*m.c.qk_rope-1]=2.0f;
}
- printf("OK kv_alloc re-allocation\n");
+ /* KV8: the f32 -> fp8 transition frees the f32 rows and allocates the byte
+ * cache + per-row scales; a second KV8 kv_alloc re-runs the fp8 free path;
+ * switching back must survive too (the KV8 arrays are freed and nulled). */
+ g_kv8=1;
+ kv_alloc(&m,16);
+ for(int i=0;i<m.c.n_layers+1;i++){
+ if(m.Lc[i]||m.Rc[i]){ fprintf(stderr,"KV8: f32 rows must stay NULL\n"); return 1; }
+ m.Lc8[i][0]=0x7e; m.Rc8[i][0]=0x7e; m.Lsc[i][0]=1.f; m.Rsc[i][0]=1.f;
+ }
+ kv_alloc(&m,64); /* fp8 re-allocation */
+ for(int i=0;i<m.c.n_layers+1;i++){
+ m.Lc8[i][(int64_t)64*m.c.kv_lora-1]=1;
+ m.Rc8[i][(int64_t)64*m.c.qk_rope-1]=1;
+ m.Lsc[i][63]=2.f; m.Rsc[i][63]=2.f;
+ }
+ g_kv8=0;
+ kv_alloc(&m,16); /* fp8 -> f32 transition */
+ if(m.kv->Lc8||m.kv->Rc8||m.kv->Lsc||m.kv->Rsc){
+ fprintf(stderr,"KV8 arrays must be freed and nulled on the way back\n"); return 1; }
+ for(int i=0;i<m.c.n_layers+1;i++){ m.Lc[i][0]=3.0f; m.Rc[i][0]=3.0f; }
+ printf("OK kv_alloc re-allocation (f32 + KV8 fp8)\n");
return 0;
}
diff --git a/c/tests/test_kv_disk.c b/c/tests/test_kv_disk.c
new file mode 100644
index 00000000..c6c7b4a0
--- /dev/null
+++ b/c/tests/test_kv_disk.c
@@ -0,0 +1,146 @@
+/* .coli_kv round-trip: v1 (f32) and v2 (KV8 fp8+scale) records, the v1->v2
+ * upgrade path (quantize-on-load; the v1 file survives until the first save rewrites it
+ * as v2), the v2-under-f32 reject, and the format-mismatch self-heal in
+ * kv_disk_append (magic differs -> file rewritten from record 0). No model
+ * file needed: the disk paths only read c->n_layers/kv_lora/qk_rope/vocab. */
+#define main coli_glm_main_unused
+#include "../colibri.c"
+#undef main
+
+#define PATH "tests/.coli_kv_test.tmp"
+static int fails=0;
+#define CHECK(cond, ...) do{ if(!(cond)){ fails++; \
+ fprintf(stderr,"FAIL %s:%d: ",__FILE__,__LINE__); fprintf(stderr,__VA_ARGS__); fputc('\n',stderr);} }while(0)
+
+static float fill(int i,int p,int j){ return sinf(i*7.f+p*1.3f+j*0.37f)*(1.f+p); }
+
+int main(void){
+ static Model m;
+ m.c.n_layers=2; m.c.kv_lora=8; m.c.qk_rope=4; m.c.vocab=256;
+ m.kv=calloc(1,sizeof(KVState));
+ snprintf(m.kv->disk_path,sizeof(m.kv->disk_path),"%s",PATH);
+ remove(PATH); g_kvsave=1; g_draft=0;
+ int NP=5, hist[5]={11,22,33,44,55}, hist2[16]={0};
+
+ /* ---- v1: f32 append + load must round-trip exactly ---- */
+ g_kv8=0; kv_alloc(&m,16);
+ for(int i=0;i<m.c.n_layers;i++) for(int p=0;p<NP;p++){
+ for(int j=0;j<m.c.kv_lora;j++) m.Lc[i][(int64_t)p*m.c.kv_lora+j]=fill(i,p,j);
+ for(int j=0;j<m.c.qk_rope;j++) m.Rc[i][(int64_t)p*m.c.qk_rope+j]=fill(i+9,p,j);
+ }
+ kv_disk_append(&m,hist,NP);
+ CHECK(m.kv->disk_nrec==NP, "v1 append nrec=%d", m.kv->disk_nrec);
+ kv_alloc(&m,16); m.kv->disk_nrec=0; /* cache azzerata, si ricarica da disco */
+ CHECK(kv_disk_load(&m,hist2,16)==NP, "v1 load");
+ for(int p=0;p<NP;p++) CHECK(hist2[p]==hist[p], "v1 hist[%d]", p);
+ for(int i=0;i<m.c.n_layers;i++) for(int p=0;p<NP;p++)
+ for(int j=0;j<m.c.kv_lora;j++)
+ CHECK(m.Lc[i][(int64_t)p*m.c.kv_lora+j]==fill(i,p,j), "v1 Lc[%d] p%d j%d", i,p,j);
+
+ /* ---- v1 file + KV8: quantize-on-load; il file v1 resta INTATTO (un crash
+ * prima del primo save non deve perdere la conversazione) ---- */
+ if(m.kv->disk_fp){ fclose(m.kv->disk_fp); m.kv->disk_fp=NULL; } /* "riavvio" del processo */
+ g_kv8=1; kv_alloc(&m,16); m.kv->disk_nrec=0;
+ CHECK(kv_disk_load(&m,hist2,16)==NP, "v1->kv8 load");
+ CHECK(m.kv->disk_nrec==0, "v1->kv8 leaves disk_nrec=0 for the full rewrite");
+ { FILE *f=fopen(PATH,"rb"); char mg[8]={0};
+ CHECK(f && fread(mg,1,8,f)==8 && !memcmp(mg,KV_MAGIC,8),
+ "v1 file must survive the upgrade load untouched");
+ if(f) fclose(f); }
+ for(int i=0;i<m.c.n_layers;i++) for(int p=0;p<NP;p++){
+ float sc=m.Lsc[i][p];
+ for(int j=0;j<m.c.kv_lora;j++){
+ float want=fill(i,p,j), got=coli_fp8_lut[m.Lc8[i][(int64_t)p*m.c.kv_lora+j]]*sc;
+ CHECK(fabsf(got-want)<=fabsf(want)/16.f+sc*0x1p-10f+1e-7f,
+ "v1->kv8 Lc[%d] p%d j%d: %g vs %g", i,p,j,got,want);
+ }
+ }
+
+ /* ---- v2: fp8 append + load must round-trip BYTE-identical ---- */
+ kv_disk_append(&m,hist,NP);
+ CHECK(m.kv->disk_nrec==NP, "v2 append nrec=%d", m.kv->disk_nrec);
+ { FILE *f=fopen(PATH,"rb"); char mg[8]={0};
+ CHECK(f && fread(mg,1,8,f)==8 && !memcmp(mg,KV_MAGIC2,8), "v2 magic on disk");
+ if(f) fclose(f); }
+ uint8_t keepL[2][5*8]; float keepS[2][5];
+ for(int i=0;i<m.c.n_layers;i++) for(int p=0;p<NP;p++){
+ memcpy(keepL[i]+(size_t)p*m.c.kv_lora, m.Lc8[i]+(int64_t)p*m.c.kv_lora, m.c.kv_lora);
+ keepS[i][p]=m.Lsc[i][p];
+ }
+ kv_alloc(&m,16); m.kv->disk_nrec=0;
+ CHECK(kv_disk_load(&m,hist2,16)==NP, "v2 load");
+ for(int i=0;i<m.c.n_layers;i++) for(int p=0;p<NP;p++){
+ CHECK(!memcmp(m.Lc8[i]+(int64_t)p*m.c.kv_lora, keepL[i]+(size_t)p*m.c.kv_lora, m.c.kv_lora),
+ "v2 Lc8 bytes layer %d pos %d", i,p);
+ CHECK(m.Lsc[i][p]==keepS[i][p], "v2 Lsc layer %d pos %d", i,p);
+ }
+
+ /* ---- v2 sotto f32: si riparte da zero, il file NON va creduto ---- */
+ if(m.kv->disk_fp){ fclose(m.kv->disk_fp); m.kv->disk_fp=NULL; } /* "riavvio" del processo */
+ g_kv8=0; kv_alloc(&m,16); m.kv->disk_nrec=0;
+ CHECK(kv_disk_load(&m,hist2,16)==0, "v2 under f32 must be rejected");
+
+ /* ---- append con formato diverso dal file: riscrittura dal record 0 ---- */
+ for(int i=0;i<m.c.n_layers;i++) for(int p=0;p<NP;p++){
+ for(int j=0;j<m.c.kv_lora;j++) m.Lc[i][(int64_t)p*m.c.kv_lora+j]=fill(i,p,j);
+ for(int j=0;j<m.c.qk_rope;j++) m.Rc[i][(int64_t)p*m.c.qk_rope+j]=fill(i+9,p,j);
+ }
+ if(m.kv->disk_fp){ fclose(m.kv->disk_fp); m.kv->disk_fp=NULL; } /* "riavvio" del processo */
+ m.kv->disk_nrec=3; /* stantio: la magic v2 lo invalida */
+ kv_disk_append(&m,hist,NP);
+ { FILE *f=fopen(PATH,"rb"); char mg[8]={0};
+ CHECK(f && fread(mg,1,8,f)==8 && !memcmp(mg,KV_MAGIC,8), "self-heal rewrote v1 magic");
+ if(f) fclose(f); }
+ kv_alloc(&m,16); m.kv->disk_nrec=0;
+ CHECK(kv_disk_load(&m,hist2,16)==NP, "self-healed v1 load");
+ for(int p=0;p<NP;p++) CHECK(hist2[p]==hist[p], "self-heal hist[%d]", p);
+
+ /* ---- v3: KV_TQ PolarQuant append + load must round-trip BYTE-identical, plus
+ * the reject paths (v3 under f32; v3 under a different bit width). Same tiny
+ * synthetic config: kv_lora=8, qk_rope=4 (both powers of two, as TQ requires). */
+ if(m.kv->disk_fp){ fclose(m.kv->disk_fp); m.kv->disk_fp=NULL; }
+ remove(PATH);
+ g_kv8=0; g_tq=1; g_tq_bits=4;
+ kv_alloc(&m,16); m.kv->disk_nrec=0;
+ int lbb=coli_tq_row_bytes(m.c.kv_lora,g_tq_bits), rbb=coli_tq_row_bytes(m.c.qk_rope,g_tq_bits);
+ for(int i=0;i<m.c.n_layers;i++) for(int p=0;p<NP;p++){ /* populate via the producer's PolarQuant */
+ float lr[8], rr[4];
+ for(int j=0;j<m.c.kv_lora;j++) lr[j]=fill(i,p,j);
+ for(int j=0;j<m.c.qk_rope;j++) rr[j]=fill(i+9,p,j);
+ m.Lsc[i][p]=coli_tq_quant_row(lr, coli_kv_row8(m.Lc8[i],p,lbb), m.c.kv_lora, g_tq_bits);
+ m.Rsc[i][p]=coli_tq_quant_row(rr, coli_kv_row8(m.Rc8[i],p,rbb), m.c.qk_rope, g_tq_bits);
+ }
+ kv_disk_append(&m,hist,NP);
+ CHECK(m.kv->disk_nrec==NP, "v3 append nrec=%d", m.kv->disk_nrec);
+ { FILE *f=fopen(PATH,"rb"); char mg[8]={0};
+ CHECK(f && fread(mg,1,8,f)==8 && !memcmp(mg,KV_MAGIC3,8), "v3 magic on disk");
+ if(f) fclose(f); }
+ uint8_t keepL3[2][5*8], keepR3[2][5*4]; float keepLs3[2][5], keepRs3[2][5];
+ for(int i=0;i<m.c.n_layers;i++) for(int p=0;p<NP;p++){
+ memcpy(keepL3[i]+(size_t)p*lbb, coli_kv_row8(m.Lc8[i],p,lbb), lbb);
+ memcpy(keepR3[i]+(size_t)p*rbb, coli_kv_row8(m.Rc8[i],p,rbb), rbb);
+ keepLs3[i][p]=m.Lsc[i][p]; keepRs3[i][p]=m.Rsc[i][p];
+ }
+ kv_alloc(&m,16); m.kv->disk_nrec=0;
+ CHECK(kv_disk_load(&m,hist2,16)==NP, "v3 load");
+ for(int i=0;i<m.c.n_layers;i++) for(int p=0;p<NP;p++){
+ CHECK(!memcmp(coli_kv_row8(m.Lc8[i],p,lbb), keepL3[i]+(size_t)p*lbb, lbb), "v3 Lc8 bytes layer %d pos %d", i,p);
+ CHECK(!memcmp(coli_kv_row8(m.Rc8[i],p,rbb), keepR3[i]+(size_t)p*rbb, rbb), "v3 Rc8 bytes layer %d pos %d", i,p);
+ CHECK(m.Lsc[i][p]==keepLs3[i][p], "v3 Lsc layer %d pos %d", i,p);
+ CHECK(m.Rsc[i][p]==keepRs3[i][p], "v3 Rsc layer %d pos %d", i,p);
+ }
+ /* v3 under f32: reject (the file must not be believed) */
+ if(m.kv->disk_fp){ fclose(m.kv->disk_fp); m.kv->disk_fp=NULL; }
+ g_tq=0; g_kv8=0; kv_alloc(&m,16); m.kv->disk_nrec=0;
+ CHECK(kv_disk_load(&m,hist2,16)==0, "v3 under f32 must be rejected");
+ /* v3 under a DIFFERENT bit width: reject (can't decode 4-bit angles as 3-bit) */
+ if(m.kv->disk_fp){ fclose(m.kv->disk_fp); m.kv->disk_fp=NULL; }
+ g_tq=1; g_tq_bits=3; kv_alloc(&m,16); m.kv->disk_nrec=0;
+ CHECK(kv_disk_load(&m,hist2,16)==0, "v3 under different bit width must be rejected");
+ g_tq=0;
+
+ remove(PATH);
+ if(fails){ fprintf(stderr,"%d failure(s)\n",fails); return 1; }
+ printf("OK kv_disk v1/v2 round-trip + upgrade + reject + self-heal\n");
+ return 0;
+}
diff --git a/c/tests/test_kv_fp8.c b/c/tests/test_kv_fp8.c
new file mode 100644
index 00000000..c4ed0218
--- /dev/null
+++ b/c/tests/test_kv_fp8.c
@@ -0,0 +1,88 @@
+/* e4m3 KV8: the encoder and the decode LUT must agree exactly. The whole
+ * fp8 code space is tiny (256 codes), so the round-trip is tested EXHAUSTIVELY:
+ * encode(decode(b)) == b for every representable byte. On top of that:
+ * round-to-nearest-even at mantissa midpoints, ±448 saturation, the per-row
+ * amax quantizer's error bound, and the coli_kv_row8 arithmetic twin. */
+#include <stdio.h>
+#include <stdlib.h>
+#include <math.h>
+#include "../kv_fp8.h"
+#include "../decode_batch.h"
+
+static int fails=0;
+#define CHECK(cond, ...) do{ if(!(cond)){ fails++; \
+ fprintf(stderr,"FAIL %s:%d: ",__FILE__,__LINE__); fprintf(stderr,__VA_ARGS__); fputc('\n',stderr);} }while(0)
+
+int main(void){
+ coli_fp8_lut_init();
+
+ /* exhaustive round-trip on every code except the NaN patterns (0x7F/0xFF,
+ * decoded as 0 by design, never produced by the encoder) */
+ for(int b=0;b<256;b++){
+ if((b&0x7F)==0x7F) continue; /* NaN codes: decoded as 0, never produced */
+ uint8_t e=coli_fp8_enc(coli_fp8_lut[b]);
+ CHECK(e==(uint8_t)b, "roundtrip byte 0x%02x -> %g -> 0x%02x", b, coli_fp8_lut[b], e);
+ }
+
+ /* saturation and specials */
+ CHECK(coli_fp8_enc(448.f)==0x7E, "448 is the max normal");
+ CHECK(coli_fp8_enc(-448.f)==0xFE, "-448");
+ CHECK(coli_fp8_enc(1000.f)==0x7E, "overflow saturates");
+ CHECK(coli_fp8_enc(-1e30f)==0xFE, "negative overflow saturates");
+ CHECK(coli_fp8_enc(INFINITY)==0x7E, "+inf saturates");
+ CHECK(coli_fp8_enc(NAN)==0x00, "NaN stored as inert 0");
+ CHECK(coli_fp8_enc(0.f)==0x00 && coli_fp8_enc(-0.f)==0x80, "signed zeros preserved");
+
+ /* round-to-nearest-even at midpoints: steps of 2 in [16,32) (E=11).
+ * 17 ties between 16 (mant 0, even) and 18 (mant 1, odd) -> 16;
+ * 19 ties between 18 (mant 1) and 20 (mant 2, even) -> 20. */
+ CHECK(coli_fp8_lut[coli_fp8_enc(17.f)]==16.f, "RNE tie 17 -> 16, got %g", coli_fp8_lut[coli_fp8_enc(17.f)]);
+ CHECK(coli_fp8_lut[coli_fp8_enc(19.f)]==20.f, "RNE tie 19 -> 20, got %g", coli_fp8_lut[coli_fp8_enc(19.f)]);
+ CHECK(coli_fp8_lut[coli_fp8_enc(17.1f)]==18.f, "17.1 -> 18");
+ /* denormal boundary: half of the smallest denormal (2^-10) ties to 0 (even) */
+ CHECK(coli_fp8_enc(0x1p-10f)==0x00, "2^-10 ties to even 0");
+ CHECK(coli_fp8_enc(0x1.8p-10f)==0x01, "0.75*2^-9 rounds up to the first denormal");
+ /* mantissa overflow across the exponent boundary: just below 2^-6 */
+ CHECK(coli_fp8_lut[coli_fp8_enc(0x1.fcp-7f)]==0x1p-6f, "denormal grid rounds up into the first normal");
+ /* binade-boundary tie WITH mantissa carry (k==16 -> k=8,E++): 15.5 lies exactly
+ * between 15 (M=7, odd) and 16 (next binade, M=0, even) -> RNE must carry to 16.
+ * The exhaustive roundtrip never triggers this (grid points encode carry-free). */
+ CHECK(coli_fp8_lut[coli_fp8_enc(15.5f)]==16.f, "RNE tie 15.5 -> 16 (mantissa carry), got %g",
+ coli_fp8_lut[coli_fp8_enc(15.5f)]);
+ CHECK(coli_fp8_lut[coli_fp8_enc(15.9f)]==16.f, "15.9 rounds up across the binade");
+ CHECK(coli_fp8_lut[coli_fp8_enc(0x1.dp3f)]==14.f, "14.5 ties down to even 14");
+
+ /* per-row quantizer: amax maps exactly to ±448*scale, error bounded by
+ * |x|/16 (3 mantissa bits) + half a denormal step (scale*2^-10) */
+ enum { N=576 };
+ float row[N]; uint8_t q[N]; float deq[N];
+ for(int i=0;i<N;i++) row[i]=sinf(0.7f*i)*expf(-((i%37)*0.21f))*(i%2?1.f:-1.f)*3.7f;
+ row[123]=-9.25f; /* the amax, negative on purpose */
+ float scale=coli_kv8_quant_row(row,q,N);
+ CHECK(fabsf(scale-9.25f/448.f)<1e-9f, "scale = amax/448 (got %g)", scale);
+ coli_kv8_dequant_row(q,scale,deq,N);
+ CHECK(deq[123]==-9.25f || fabsf(deq[123]+9.25f)<=9.25f*1e-6f, "amax survives the trip (got %g)", deq[123]);
+ for(int i=0;i<N;i++){
+ float err=fabsf(deq[i]-row[i]), bound=fabsf(row[i])/16.f+scale*0x1p-10f+1e-7f;
+ CHECK(err<=bound, "elem %d: |%g - %g| = %g > bound %g", i, deq[i], row[i], err, bound);
+ }
+
+ /* all-zero row: bytes 0, scale 1 (no fabricated 1/0) */
+ float zrow[8]={0}; uint8_t zq[8];
+ CHECK(coli_kv8_quant_row(zrow,zq,8)==1.f, "zero row keeps scale 1");
+ for(int i=0;i<8;i++) CHECK(zq[i]==0, "zero row byte %d", i);
+ /* subnormal amax: 448/amax would overflow to +inf and saturate every nonzero
+ * element to ±448 — the guard must treat the row as zero instead */
+ float tiny[4]={1e-38f,-1e-38f,0,1e-40f}; uint8_t tq[4];
+ CHECK(coli_kv8_quant_row(tiny,tq,4)==1.f, "subnormal row keeps scale 1");
+ for(int i=0;i<4;i++) CHECK(tq[i]==0, "subnormal row byte %d", i);
+
+ /* row accessor twin: same arithmetic as coli_kv_row, byte-typed */
+ uint8_t buf[7*5];
+ CHECK(coli_kv_row8(buf,4,7)==buf+28, "coli_kv_row8 arithmetic");
+ CHECK(coli_kv_row8(buf,0,7)==buf, "coli_kv_row8 row 0");
+
+ if(fails){ fprintf(stderr,"%d failure(s)\n",fails); return 1; }
+ printf("OK kv_fp8 e4m3 (exhaustive roundtrip + RNE + row quant)\n");
+ return 0;
+}
diff --git a/c/tests/test_kv_tq.c b/c/tests/test_kv_tq.c
new file mode 100644
index 00000000..c65409e0
--- /dev/null
+++ b/c/tests/test_kv_tq.c
@@ -0,0 +1,279 @@
+/* PolarQuant KV tier (kv_tq.h). The rotation must be orthonormal and self-inverse,
+ * the polar transform must preserve the radius EXACTLY (only the direction is lossy),
+ * the angle grids must round-trip their own centroids, and the packed row must
+ * survive quant->dequant. Distortion is data-oblivious: because the randomized
+ * Hadamard rotation gaussianizes ANY input, even a one-hot vector reconstructs well.
+ * Everything is deterministic (fixed seed), so no calibration and no fixtures. */
+#include <stdio.h>
+#include <stdlib.h>
+#include <math.h>
+#include <string.h>
+#include "../kv_tq.h"
+
+static int fails=0;
+#define CHECK(cond, ...) do{ if(!(cond)){ fails++; \
+ fprintf(stderr,"FAIL %s:%d: ",__FILE__,__LINE__); fprintf(stderr,__VA_ARGS__); fputc('\n',stderr);} }while(0)
+
+/* deterministic pseudo-random floats (no libc rand: reproducible across platforms) */
+static uint32_t rng=0x12345678u;
+static float frand(void){ rng=rng*1664525u+1013904223u; return (float)((rng>>8)&0xFFFFFF)/(float)0x1000000 * 2.f - 1.f; }
+static float gauss(void){ /* Box-Muller-ish from two uniforms */
+ float u=(frand()+1.f)*0.5f+1e-7f, v=(frand()+1.f)*0.5f;
+ return sqrtf(-2.f*logf(u))*cosf(2.f*COLI_TQ_PI*v);
+}
+
+static float norm2(const float *a,int n){ double s=0; for(int i=0;i<n;i++) s+=(double)a[i]*a[i]; return (float)sqrt(s); }
+static float l2diff(const float *a,const float *b,int n){ double s=0; for(int i=0;i<n;i++){ double d=(double)a[i]-b[i]; s+=d*d; } return (float)sqrt(s); }
+
+/* average relative L2 reconstruction error over many random Gaussian rows */
+static float avg_relerr(int n,int bits,int rows){
+ int rb=coli_tq_row_bytes(n,bits);
+ float *x=malloc(sizeof(float)*n), *y=malloc(sizeof(float)*n); uint8_t *q=malloc(rb);
+ double acc=0;
+ for(int r=0;r<rows;r++){
+ for(int i=0;i<n;i++) x[i]=gauss()*3.7f;
+ float rad=coli_tq_quant_row(x,q,n,bits);
+ coli_tq_dequant_row(q,rad,y,n,bits);
+ float nx=norm2(x,n); acc += (nx>0)? l2diff(x,y,n)/nx : 0;
+ }
+ free(x); free(y); free(q);
+ return (float)(acc/rows);
+}
+
+int main(void){
+ /* ---- FWHT is normalized and self-inverse ---- */
+ for(int n=2; n<=1024; n<<=1){
+ float a[1024], b[1024];
+ for(int i=0;i<n;i++){ a[i]=gauss(); b[i]=a[i]; }
+ coli_tq_fwht(b,n); coli_tq_fwht(b,n);
+ float e=l2diff(a,b,n), na=norm2(a,n);
+ CHECK(e <= 1e-4f*(na+1.f), "FWHT self-inverse n=%d: err %g", n, e);
+ /* one application preserves the L2 norm (orthonormal) */
+ for(int i=0;i<n;i++) b[i]=a[i];
+ coli_tq_fwht(b,n);
+ CHECK(fabsf(norm2(b,n)-na) <= 1e-4f*(na+1.f), "FWHT preserves norm n=%d", n);
+ }
+
+ /* ---- rotate/unrotate is the identity and preserves the norm ---- */
+ for(int n=2; n<=1024; n<<=1){
+ float x[1024], y[1024], z[1024];
+ for(int i=0;i<n;i++) x[i]=gauss()*2.5f;
+ coli_tq_rotate(x,y,n,COLI_TQ_SEED);
+ CHECK(fabsf(norm2(y,n)-norm2(x,n)) <= 1e-4f*(norm2(x,n)+1.f), "rotate preserves norm n=%d", n);
+ memcpy(z,y,sizeof(float)*n);
+ coli_tq_unrotate(z,n,COLI_TQ_SEED);
+ CHECK(l2diff(x,z,n) <= 1e-4f*(norm2(x,n)+1.f), "rotate->unrotate identity n=%d", n);
+ }
+
+ /* ---- angle grids round-trip their own codes (centroid re-encodes to itself) ---- */
+ for(int b=1;b<=6;b++){
+ for(uint32_t c=0;c<(1u<<b);c++){
+ float ctr=coli_tq_dec1(c,b);
+ CHECK(coli_tq_enc1(ctr,b)==c, "level-1 grid b=%d code %u", b, c);
+ }
+ for(int lvl=2; lvl<=9; lvl++){
+ for(uint32_t c=0;c<(1u<<b);c++){
+ float ctr=coli_tq_dec2(c,b,lvl);
+ CHECK(coli_tq_enc2(ctr,b,lvl)==c, "centered grid b=%d lvl=%d code %u", b, lvl, c);
+ }
+ }
+ }
+
+ /* ---- bit-cursor packs and unpacks any width losslessly ---- */
+ {
+ uint8_t buf[64]; memset(buf,0,sizeof(buf));
+ int wpos=0; uint32_t vals[20];
+ for(int i=0;i<20;i++){ int w=1+(i%6); vals[i]=coli_tq_hash((uint32_t)i)&((1u<<w)-1); coli_tq_wbits(buf,&wpos,vals[i],w); }
+ int rpos=0;
+ for(int i=0;i<20;i++){ int w=1+(i%6); uint32_t v=coli_tq_rbits(buf,&rpos,w); CHECK(v==vals[i], "bitcursor i=%d w=%d %u!=%u", i, w, v, vals[i]); }
+ CHECK(wpos==rpos, "bitcursor cursor mismatch %d %d", wpos, rpos);
+ }
+
+ /* ---- row_bytes matches the hand count: (n/2)*b1 + (n/2-1)*b2 bits ---- */
+ CHECK(coli_tq_row_bytes(512,4)==(256*4+255*3+7)/8, "row_bytes 512/4 = %d", coli_tq_row_bytes(512,4));
+ CHECK(coli_tq_row_bytes(512,3)==(256*3+255*2+7)/8, "row_bytes 512/3 = %d", coli_tq_row_bytes(512,3));
+ CHECK(coli_tq_row_bytes(64,4) ==( 32*4+ 31*3+7)/8, "row_bytes 64/4 = %d", coli_tq_row_bytes(64,4));
+ /* it must be smaller than the KV8 byte count (n bytes/row) — that's the point */
+ CHECK(coli_tq_row_bytes(512,4) < 512, "TQ4 row < KV8 row (512): %d", coli_tq_row_bytes(512,4));
+
+ /* ---- full-row round-trip: radius EXACT, direction lossy but bounded ---- */
+ for(int n=64; n<=512; n<<=1){
+ for(int bits=3; bits<=4; bits++){
+ int rb=coli_tq_row_bytes(n,bits);
+ float x[512], y[512]; uint8_t q[512];
+ for(int i=0;i<n;i++) x[i]=gauss()*3.7f;
+ float rad=coli_tq_quant_row(x,q,n,bits);
+ CHECK(fabsf(rad-norm2(x,n))<=1e-4f*norm2(x,n), "radius==||x|| n=%d bits=%d (%g vs %g)", n, bits, rad, norm2(x,n));
+ coli_tq_dequant_row(q,rad,y,n,bits);
+ CHECK(fabsf(norm2(y,n)-rad)<=1e-3f*rad, "recon preserves radius n=%d bits=%d (%g vs %g)", n, bits, norm2(y,n), rad);
+ (void)rb;
+ }
+ }
+
+ /* ---- full-pipeline DIRECTION coverage at every production size ----
+ * norm preservation alone is a tautology (decode is radius-preserving by
+ * construction), so a wrong seed / wrong angle-offset in decode would corrupt
+ * direction while ||y|| stayed exactly right. avg_relerr compares x vs y
+ * element-wise, so it — and only it — catches that. n=64 is the real qk_rope
+ * width, n=512 the kv_lora latent; both must have direction coverage. */
+ for(int n=64; n<=512; n<<=1){
+ float e3=avg_relerr(n,3,150), e4=avg_relerr(n,4,150);
+ CHECK(e4 < e3, "n=%d: more bits -> less distortion (e4=%g e3=%g)", n, e4, e3);
+ CHECK(e4 < 0.45f, "n=%d: TQ4 mean rel err small (%g)", n, e4);
+ CHECK(e3 < 0.65f, "n=%d: TQ3 mean rel err bounded (%g)", n, e3);
+ fprintf(stderr,"[info] mean rel L2 err n=%d: TQ3=%.4f TQ4=%.4f\n", n, e3, e4);
+ }
+
+ /* ---- preconditioning handles adversarial (non-Gaussian) input ----
+ * a one-hot vector rotates to Hadamard-column form (all coords +-1/sqrt(n)), so
+ * its deeper sub-radii are all equal and those angles land exactly on pi/4 (a
+ * grid center). The level-1 angles sit at +-pi/4, midway between the uniform
+ * bins, so error stays at the same grid floor as Gaussian input (not worse) —
+ * the point is a maximally-spread input still round-trips with bounded error and
+ * an EXACT radius, never a NaN. */
+ {
+ int n=256, bits=4, rb=coli_tq_row_bytes(n,bits);
+ float x[256]={0}, y[256]; uint8_t *q=malloc(rb);
+ x[97]=1.f;
+ float rad=coli_tq_quant_row(x,q,n,bits);
+ coli_tq_dequant_row(q,rad,y,n,bits);
+ CHECK(fabsf(rad-1.f)<1e-5f, "one-hot radius 1 (%g)", rad);
+ CHECK(l2diff(x,y,n) < 0.35f, "one-hot round-trips within the grid floor (%g)", l2diff(x,y,n));
+ free(q);
+ }
+
+ /* ---- inert rows: zero / NaN / Inf / subnormal -> radius 0, decode all-zero ---- */
+ {
+ int n=64, bits=4, rb=coli_tq_row_bytes(n,bits);
+ float x[64], y[64]; uint8_t *q=malloc(rb);
+ /* zero */
+ memset(x,0,sizeof(float)*n);
+ CHECK(coli_tq_quant_row(x,q,n,bits)==0.f, "zero row radius 0");
+ coli_tq_dequant_row(q,0.f,y,n,bits);
+ for(int i=0;i<n;i++) CHECK(y[i]==0.f, "zero row decode [%d]", i);
+ /* NaN poisons the norm -> inert */
+ for(int i=0;i<n;i++) x[i]=gauss(); x[7]=NAN;
+ CHECK(coli_tq_quant_row(x,q,n,bits)==0.f, "NaN row -> inert radius 0");
+ /* Inf -> inert */
+ for(int i=0;i<n;i++) x[i]=gauss(); x[7]=INFINITY;
+ CHECK(coli_tq_quant_row(x,q,n,bits)==0.f, "Inf row -> inert radius 0");
+ /* subnormal-magnitude row: norm below the guard -> inert (like KV8) */
+ for(int i=0;i<n;i++) x[i]=1e-38f;
+ CHECK(coli_tq_quant_row(x,q,n,bits)==0.f, "subnormal row -> inert radius 0");
+ /* a non-finite radius read from a corrupt file decodes to zero, never NaN */
+ for(int i=0;i<n;i++) x[i]=gauss();
+ float rad=coli_tq_quant_row(x,q,n,bits);
+ coli_tq_dequant_row(q,NAN,y,n,bits);
+ for(int i=0;i<n;i++) CHECK(y[i]==0.f, "NaN radius decodes to zero [%d]", i);
+ (void)rad;
+ free(q);
+ }
+
+ /* ---- rotated int4 codec (coli_q4): radius exact, LOWER distortion than polar at 4-bit,
+ * full reconstruction, inert rows. This is the competitive 4-bit tier. ---- */
+ for(int n=64; n<=512; n<<=1){
+ CHECK(coli_q4_row_bytes(n)==n/2, "q4 row bytes n/2 (n=%d)", n);
+ double sq=0, sp=0; int rows=200;
+ for(int r=0;r<rows;r++){
+ float x[512], y[512], yp[512]; uint8_t q[256], qp[512];
+ for(int i=0;i<n;i++) x[i]=gauss()*3.7f;
+ float rad=coli_q4_quant_row(x,q,n); coli_q4_dequant_row(q,rad,y,n);
+ float radp=coli_tq_quant_row(x,qp,n,4); coli_tq_dequant_row(qp,radp,yp,n,4);
+ /* radius stored = ||x|| exactly; unlike polar, int4 recon does NOT preserve the norm
+ * (each coord is quantized), so only check the stored radius here. */
+ if(r==0) CHECK(fabsf(rad-norm2(x,n))<=1e-4f*norm2(x,n), "q4 radius==||x|| n=%d", n);
+ sq += l2diff(x,y,n)/norm2(x,n); sp += l2diff(x,yp,n)/norm2(x,n);
+ }
+ sq/=rows; sp/=rows;
+ CHECK(sq < sp, "n=%d: rotated-int4 beats PolarQuant at 4-bit (%.4f vs %.4f)", n, sq, sp);
+ fprintf(stderr,"[info] rel L2 err n=%d: int4=%.4f polar4=%.4f\n", n, sq, sp);
+ }
+ { int n=128; float x[128], y[128]; uint8_t q[64];
+ memset(x,0,sizeof(float)*n); CHECK(coli_q4_quant_row(x,q,n)==0.f, "q4 zero row inert");
+ coli_q4_dequant_row(q,0.f,y,n); for(int i=0;i<n;i++) CHECK(y[i]==0.f, "q4 zero decode [%d]", i);
+ for(int i=0;i<n;i++) x[i]=gauss(); x[3]=NAN; CHECK(coli_q4_quant_row(x,q,n)==0.f, "q4 NaN row inert");
+ for(int i=0;i<n;i++) x[i]=gauss(); x[3]=INFINITY; CHECK(coli_q4_quant_row(x,q,n)==0.f, "q4 Inf row inert"); }
+
+ /* ---- codec-1 score/context ORTHOGONALITY IDENTITY (the basis of the native fused TQ4
+ * attention kernels a_score_tq / a_clat_tq — Metal and CUDA). The rotated-int4 recon is
+ * x_hat = unrotate(c) with c_i = coli_q4_lev[code_i]*std, std = radius/sqrt(n). Because the
+ * randomized-Hadamard rotate/unrotate are adjoint orthonormal maps, WITHOUT reconstructing
+ * any row:
+ * score: q . x_hat == rotate(q) . c (dot packed nibbles + a per-row std)
+ * context: sum_t w_t . x_hat_t == unrotate(sum_t w_t . c_t) (accumulate, then unrotate once)
+ * The native kernels compute exactly the right-hand sides, so this test is what guards their
+ * math: a wrong sign seed, FWHT normalization, or std would break the identity here. */
+ for(int n=64; n<=512; n<<=1){
+ float x[512], xhat[512], qv[512], qtil[512]; uint8_t packed[256];
+ /* metric: |direct-native| relative to the Cauchy-Schwarz score scale ||q~||*||x_hat||,
+ * NOT to |direct| (which can cancel to ~0 and blow up a tiny absolute error — irrelevant
+ * to the identity and to softmax, which sees the absolute score). */
+ double worst_score=0;
+ for(int r=0;r<128;r++){
+ for(int i=0;i<n;i++){ x[i]=gauss()*3.1f; qv[i]=gauss()*1.7f; }
+ float rad=coli_q4_quant_row(x,packed,n);
+ coli_q4_dequant_row(packed,rad,xhat,n);
+ float direct=0; for(int i=0;i<n;i++) direct+=qv[i]*xhat[i];
+ coli_tq_rotate(qv,qtil,n,COLI_TQ_SEED); /* q~ = rotate(q) */
+ float std=rad/sqrtf((float)n), native=0;
+ for(int i=0;i<n;i++){ int code=(packed[i>>1]>>((i&1)*4))&0xF; native += qtil[i]*coli_q4_lev[code]*std; }
+ double scale=(double)norm2(qtil,n)*norm2(xhat,n)+1e-6;
+ double rel=fabs(direct-native)/scale;
+ if(rel>worst_score) worst_score=rel;
+ }
+ CHECK(worst_score < 1e-5, "n=%d: score identity q.x_hat==rotate(q).c (worst rel %g)", n, worst_score);
+
+ int T=17; float w, acc[512], ctx_native[512], ctx_direct[512];
+ memset(acc,0,sizeof(float)*n); memset(ctx_direct,0,sizeof(float)*n);
+ for(int t=0;t<T;t++){
+ for(int i=0;i<n;i++) x[i]=gauss()*2.4f;
+ float rad=coli_q4_quant_row(x,packed,n);
+ coli_q4_dequant_row(packed,rad,xhat,n);
+ w=frand(); float std=rad/sqrtf((float)n);
+ for(int i=0;i<n;i++){ ctx_direct[i]+=w*xhat[i];
+ int code=(packed[i>>1]>>((i&1)*4))&0xF; acc[i]+=w*std*coli_q4_lev[code]; }
+ }
+ memcpy(ctx_native,acc,sizeof(float)*n);
+ coli_tq_unrotate(ctx_native,n,COLI_TQ_SEED); /* unrotate(sum w c) */
+ CHECK(l2diff(ctx_direct,ctx_native,n) < 1e-4f*(norm2(ctx_direct,n)+1.f),
+ "n=%d: context identity sum w.x_hat==unrotate(sum w.c) (%g)", n, l2diff(ctx_direct,ctx_native,n));
+ }
+
+ /* ---- END-TO-END MLA consumer (mirrors glm.c's codec-1 CPU attention path): score over L
+ * (kvl=512) + R (rope=64), softmax, context over L. Computed BOTH ways — dequant-then-dot
+ * (reference) vs rotate-query-then-nibble-dot (the native path) — must match. This guards the
+ * exact transcription in glm.c (nibble unpack, L+R std scaling, unrotate placement). ---- */
+ {
+ const int kvl=512, rope=64, T=23; const uint32_t SEED=COLI_TQ_SEED;
+ float qabs[512], qr[64]; for(int i=0;i<kvl;i++) qabs[i]=gauss()*1.3f; for(int d=0;d<rope;d++) qr[d]=gauss()*1.1f;
+ uint8_t Lc[512*256], Rc[64*32]; float Lsc[64], Rsc[64]; /* T<=64 rows */
+ int lrb=coli_q4_row_bytes(kvl), rrb=coli_q4_row_bytes(rope);
+ for(int t=0;t<T;t++){ float lf[512], rf[64];
+ for(int i=0;i<kvl;i++) lf[i]=gauss()*2.2f; for(int d=0;d<rope;d++) rf[d]=gauss()*1.7f;
+ Lsc[t]=coli_q4_quant_row(lf,&Lc[(size_t)t*lrb],kvl); Rsc[t]=coli_q4_quant_row(rf,&Rc[(size_t)t*rrb],rope); }
+ /* reference: dequant each row to f32, dot */
+ float scR[64], ctxR[512]; memset(ctxR,0,sizeof(float)*kvl);
+ for(int t=0;t<T;t++){ float Lf[512], Rf[64];
+ coli_q4_dequant_row(&Lc[(size_t)t*lrb],Lsc[t],Lf,kvl); coli_q4_dequant_row(&Rc[(size_t)t*rrb],Rsc[t],Rf,rope);
+ float a=0; for(int i=0;i<kvl;i++) a+=qabs[i]*Lf[i]; for(int d=0;d<rope;d++) a+=qr[d]*Rf[d]; scR[t]=a; }
+ { float mx=-1e30f; for(int t=0;t<T;t++) mx=fmaxf(mx,scR[t]); float sm=0; for(int t=0;t<T;t++){ scR[t]=expf(scR[t]-mx); sm+=scR[t]; } for(int t=0;t<T;t++) scR[t]/=sm; }
+ for(int t=0;t<T;t++){ float Lf[512]; coli_q4_dequant_row(&Lc[(size_t)t*lrb],Lsc[t],Lf,kvl); for(int i=0;i<kvl;i++) ctxR[i]+=scR[t]*Lf[i]; }
+ /* native: rotate q once, dot packed nibbles, unrotate the accumulator once */
+ float qtl[512], qtr[64]; coli_tq_rotate(qabs,qtl,kvl,SEED); coli_tq_rotate(qr,qtr,rope,SEED);
+ float invsnL=1.f/sqrtf((float)kvl), invsnR=1.f/sqrtf((float)rope);
+ float scN[64], ctxN[512]; memset(ctxN,0,sizeof(float)*kvl);
+ for(int t=0;t<T;t++){ const uint8_t*Lt=&Lc[(size_t)t*lrb]; const uint8_t*Rt=&Rc[(size_t)t*rrb];
+ float al=0,ar=0; for(int i=0;i<kvl;i++){ int cc=(Lt[i>>1]>>((i&1)*4))&0xF; al+=qtl[i]*coli_q4_lev[cc]; }
+ for(int d=0;d<rope;d++){ int cc=(Rt[d>>1]>>((d&1)*4))&0xF; ar+=qtr[d]*coli_q4_lev[cc]; }
+ scN[t]=al*Lsc[t]*invsnL + ar*Rsc[t]*invsnR; }
+ { float mx=-1e30f; for(int t=0;t<T;t++) mx=fmaxf(mx,scN[t]); float sm=0; for(int t=0;t<T;t++){ scN[t]=expf(scN[t]-mx); sm+=scN[t]; } for(int t=0;t<T;t++) scN[t]/=sm; }
+ for(int t=0;t<T;t++){ const uint8_t*Lt=&Lc[(size_t)t*lrb]; float a=scN[t]*Lsc[t]*invsnL;
+ for(int i=0;i<kvl;i++){ int cc=(Lt[i>>1]>>((i&1)*4))&0xF; ctxN[i]+=a*coli_q4_lev[cc]; } }
+ coli_tq_unrotate(ctxN,kvl,SEED);
+ CHECK(l2diff(ctxR,ctxN,kvl) < 1e-4f*(norm2(ctxR,kvl)+1.f), "MLA consumer native==dequant (ctx %g)", l2diff(ctxR,ctxN,kvl));
+ }
+
+ if(fails){ fprintf(stderr,"%d failure(s)\n",fails); return 1; }
+ printf("OK kv_tq (PolarQuant + rotated-int4 codec: rotation, roundtrip, distortion, inert rows)\n");
+ return 0;
+}
diff --git a/docs/ENVIRONMENT.md b/docs/ENVIRONMENT.md
index b49dc714..7177f301 100644
--- a/docs/ENVIRONMENT.md
+++ b/docs/ENVIRONMENT.md
@@ -49,6 +49,8 @@ Format: `VAR` — default — effect.
| `SEED` | unset → seeded from clock + PID | RNG seed for sampling. **Unset = different every run.** Set a fixed value for reproducible sampling. |
| `KVSAVE` | `1` (on) | Persist the KV cache to `<model>/.coli_kv` so a conversation reopens warm. `KVSAVE=0` disables save+load (lossless round-trip; does not change output). |
| `KV_SLOTS` | `1` | Number of independent KV conversation slots (1–16), used in serve mode. |
+| `KV8` | `0` (off) | Store the MLA latent KV cache in fp8 e4m3 with a per-row scale: ~3.9× less KV RAM, and `.coli_kv` shrinks ~4× (saved as the v2 format; f32 v1 files are quantized on resume and rewritten). Adds DeepSeek-V3-class KV quantization noise to attention. CPU attention path only for now: the CUDA/Metal fused-attention fast paths read f32 KV rows, so under KV8 they fall back to the CPU consumer (native fp8 decode; a one-time notice is printed under `COLI_CUDA_ATTN=1`). Forces `COLI_CUDA_PIPE=0`. Native CUDA/Metal fp8-KV kernels are follow-up PRs. |
+| `KV_TQ` | `0` (off) | Sub-byte MLA latent KV quantization, mutually exclusive with `KV8` (`KV_TQ` wins). `KV_TQ=4` is the recommended tier: rotated-int4 codec (randomized-Hadamard rotation + Lloyd codebook, per-row radius as the scale), ~7.6× less KV RAM than f32. `KV_TQ=2|3|5|6` selects the PolarQuant codec at that bit width (`KV_TQ_POLAR=1` forces PolarQuant at 4 bits too). Requires power-of-two row widths (`kv_lora`/`qk_rope`; the GLM MLA shapes 512/64 qualify). `.coli_kv` is saved as the v3 format; a file saved under a different KV mode, codec, or bit width is refused with an explicit message and the cache restarts. Same CPU-only status as `KV8`: GPU fast paths fall back to the CPU consumer; native kernels are follow-up PRs. Forces `COLI_CUDA_PIPE=0`. |
| `THINK` | `0` (off) | Emit a `<think>` reasoning block. `THINK=1` turns on visible reasoning. |
| `MTP` | on | Multi-Token Prediction (speculative draft head). `MTP=0` disables it. |