Elffuss BraidHub

kikocis/coco public

main · 25.0 KiBRawPermalink
1// coco turboquant-v2 — data-free weight quantization, pure Rust.
2//
3// Clean-room port of the validated POC math (lab/coco/poc/turboquant_v2.py):
4// 1. Pad input dim of W (out,in) to next power of two P; multiply by a fixed
5// ±1 sign vector seeded by a constant; apply an orthonormal Fast
6// Walsh-Hadamard Transform along the (padded) input dim. This "incoherence
7// rotation" spreads outliers across all coords so a single Gaussian
8// codebook fits every weight matrix (concentration of measure on the sphere).
9// 2. Flatten the rotated rows and split into blocks of d=128. Per block compute
10// an fp16 RMS *radius*; normalize the block by the radius so coords ~ N(0,1).
11// 3. Quantize each normalized coord to the nearest level of a precomputed
12// Lloyd-Max N(0,1) codebook (bits=3 → 8 levels).
13// 4. (Optional) outlier split: keep the top `outlier_frac` |rotated| values in
14// fp16 in a sparse side-list; zero them before block quantization.
15//
16// Decode = codebook lookup → ×radius → restore outliers → inverse FWHT (same
17// butterfly, it's self-inverse) → ×signs → crop to `inn` columns.
18//
19// NO Python, NO llama.cpp, NO external quant libs. FWHT + codebook + (de)quant
20// are all implemented here. f16 is provided by candle's re-exported `half` crate.
21
22use half::f16;
23
24/// Lloyd-Max optimal scalar quantizer for N(0,1) at bits=3 (8 levels), sorted.
25/// Computed once via Lloyd's algorithm on Gaussian samples in the POC; the values
26/// are stable across seeds so we ship them as a const (matches turboquant.py's
27/// `lloyd_max_gaussian(3)`). `codebook_for_bits` can rebuild any table at runtime.
28pub const LLOYD_MAX_3BIT: [f32; 8] = [
29 -2.152_152_3,
30 -1.348_969_7,
31 -0.762_198_9,
32 -0.250_466_1,
33 0.240_071_25,
34 0.751_659_1,
35 1.339_368_1,
36 2.149_770_1,
37];
38
39/// Build a Lloyd-Max N(0,1) codebook with 2^bits levels at runtime (Lloyd's
40/// algorithm / k-means on Gaussian samples). Used as a fallback / for other bit
41/// widths; bits=3 uses the const table by default for determinism & speed.
42pub fn codebook_for_bits(bits: u32, iters: usize, n_samples: usize, seed: u64) -> Vec<f32> {
43 // Deterministic Gaussian samples via a tiny splitmix64 + Box-Muller.
44 let mut state = seed.wrapping_add(0x9E37_79B9_7F4A_7C15);
45 let mut next_u64 = || {
46 state = state.wrapping_add(0x9E37_79B9_7F4A_7C15);
47 let mut z = state;
48 z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
49 z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
50 z ^ (z >> 31)
51 };
52 let mut next_unit = || (next_u64() >> 11) as f64 / (1u64 << 53) as f64;
53 let mut samples = Vec::with_capacity(n_samples);
54 while samples.len() < n_samples {
55 // Box-Muller; clamp u1 away from 0 to avoid ln(0).
56 let u1 = next_unit().max(1e-12);
57 let u2 = next_unit();
58 let r = (-2.0 * u1.ln()).sqrt();
59 let theta = std::f64::consts::TAU * u2;
60 samples.push((r * theta.cos()) as f32);
61 if samples.len() < n_samples {
62 samples.push((r * theta.sin()) as f32);
63 }
64 }
65 samples.sort_by(|a, b| a.partial_cmp(b).unwrap());
66
67 let k = 1usize << bits;
68 // Init centroids at quantiles for stable convergence.
69 let mut c: Vec<f32> = (0..k)
70 .map(|j| {
71 let q = (j as f64 + 0.5) / k as f64;
72 let idx = ((q * samples.len() as f64) as usize).min(samples.len() - 1);
73 samples[idx]
74 })
75 .collect();
76
77 for _ in 0..iters {
78 // assign + accumulate (samples are sorted, but plain scan is fine here).
79 let mut sum = vec![0f64; k];
80 let mut cnt = vec![0u64; k];
81 let edges: Vec<f32> = (0..k - 1).map(|j| (c[j] + c[j + 1]) / 2.0).collect();
82 for &s in &samples {
83 // nearest centroid = searchsorted on midpoint edges
84 let mut j = 0usize;
85 while j < edges.len() && s > edges[j] {
86 j += 1;
87 }
88 sum[j] += s as f64;
89 cnt[j] += 1;
90 }
91 let mut max_delta = 0f32;
92 for j in 0..k {
93 if cnt[j] > 0 {
94 let newc = (sum[j] / cnt[j] as f64) as f32;
95 max_delta = max_delta.max((newc - c[j]).abs());
96 c[j] = newc;
97 }
98 }
99 if max_delta < 1e-7 {
100 break;
101 }
102 }
103 c
104}
105
106/// Fixed ±1 sign vector of length `p`, seeded by `seed` (splitmix64). Matches the
107/// POC's `_signs(P, seed)` in spirit: a deterministic, reproducible sign flip.
108///
109/// `pub(crate)` so the fast inference path (`qlinear`) can rotate the ACTIVATION
110/// with the exact same sign vector the encoder used for the weights.
111pub(crate) fn signs(p: usize, seed: u64) -> Vec<f32> {
112 let mut state = seed.wrapping_add(0x9E37_79B9_7F4A_7C15);
113 let mut out = Vec::with_capacity(p);
114 for _ in 0..p {
115 state = state.wrapping_add(0x9E37_79B9_7F4A_7C15);
116 let mut z = state;
117 z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
118 z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
119 z ^= z >> 31;
120 out.push(if z & 1 == 0 { 1.0 } else { -1.0 });
121 }
122 out
123}
124
125/// In-place orthonormal Fast Walsh-Hadamard Transform on `x` (length must be a
126/// power of two). Self-inverse: applying it twice is the identity. O(n log n).
127///
128/// `pub(crate)` so `qlinear` can rotate the activation per d-wide block.
129pub(crate) fn fwht_inplace(x: &mut [f32]) {
130 let n = x.len();
131 debug_assert!(n.is_power_of_two(), "FWHT length must be a power of two");
132 let mut h = 1usize;
133 while h < n {
134 let mut i = 0usize;
135 while i < n {
136 for j in i..i + h {
137 let a = x[j];
138 let b = x[j + h];
139 x[j] = a + b;
140 x[j + h] = a - b;
141 }
142 i += 2 * h;
143 }
144 h *= 2;
145 }
146 let scale = 1.0f32 / (n as f32).sqrt();
147 for v in x.iter_mut() {
148 *v *= scale;
149 }
150}
151
152/// Quantization config.
153#[derive(Clone, Copy)]
154pub struct TqConfig {
155 pub d: usize, // block size along the flattened rotated rows
156 pub bits: u32, // codebook bits (3 → 8 levels)
157 pub outlier_frac: f32, // fraction of |rotated| values kept in fp16 (0.0 = off)
158 pub seed: u64, // sign-vector seed
159 /// Rotation mode:
160 /// false → "v2": pad input dim to next power of two P and FWHT the WHOLE
161 /// row (max quality, but codes scale with P → padding-bpw cost
162 /// when inn is not already a power of two).
163 /// true → "block": when inn is a multiple of `d`, FWHT each consecutive
164 /// d-wide sub-block of the input independently (block-diagonal
165 /// Hadamard). NO padding → exactly `bits` bpw for the codes
166 /// (~3.125 bpw at d=128/bits=3). Slightly higher recon error than
167 /// full-row rotation, equivalent to the v1 recipe's quality.
168 pub block_hadamard: bool,
169}
170
171impl Default for TqConfig {
172 fn default() -> Self {
173 Self { d: 128, bits: 3, outlier_frac: 0.005, seed: 0, block_hadamard: false }
174 }
175}
176
177/// Compressed representation of one weight matrix W (out, inn).
178pub struct TqWeight {
179 pub out: usize,
180 pub inn: usize,
181 pub p: usize, // rotated-grid columns per row (= next_pow2(inn) in v2 mode, = inn in block mode)
182 pub d: usize,
183 pub bits: u32,
184 pub seed: u64,
185 pub block_hadamard: bool, // which rotation was used (decode must match)
186 pub codes: Vec<u8>, // one code (0..2^bits) per coord of the (out*P) rotated grid
187 pub radius: Vec<f16>, // one fp16 RMS radius per block of d coords
188 pub codebook: Vec<f32>, // 2^bits levels
189 pub outlier_idx: Vec<u32>, // flat indices into the (out*P) grid kept in fp16
190 pub outlier_val: Vec<f16>, // the corresponding fp16 values (rotated space)
191}
192
193impl TqWeight {
194 /// Bytes actually needed to store this compressed weight (codes packed to
195 /// `bits` bits, fp16 radius, fp16 outlier values + u32 indices, codebook).
196 pub fn compressed_bytes(&self) -> usize {
197 let code_bits = self.codes.len() * self.bits as usize;
198 let code_bytes = code_bits.div_ceil(8);
199 let radius_bytes = self.radius.len() * 2;
200 let outlier_bytes = self.outlier_idx.len() * 4 + self.outlier_val.len() * 2;
201 let codebook_bytes = self.codebook.len() * 4;
202 code_bytes + radius_bytes + outlier_bytes + codebook_bytes
203 }
204
205 /// Effective bits-per-weight for this matrix (over the *original* inn*out
206 /// weights), matching the POC's `tq_v2_bpw` accounting.
207 pub fn bpw(&self) -> f64 {
208 let orig = (self.out * self.inn) as f64;
209 (self.compressed_bytes() * 8) as f64 / orig
210 }
211
212 /// Pack the 3-bit codes two-per-byte (4-bit nibbles, low nibble first) for
213 /// the fast GPU kernel. 3-bit codes (0..8) fit in a nibble with the top bit
214 /// unused. This is what the kernel actually reads: 4 bpw resident for codes
215 /// (vs 16 for fp16) — the matmul touches ~4× fewer bytes per weight.
216 /// Returns a `Vec<u8>` of length `ceil(codes.len()/2)`.
217 pub fn codes_packed_nibble(&self) -> Vec<u8> {
218 let n = self.codes.len();
219 let mut out = vec![0u8; n.div_ceil(2)];
220 for (i, &c) in self.codes.iter().enumerate() {
221 let byte = i / 2;
222 if i & 1 == 0 {
223 out[byte] |= c & 0x0F;
224 } else {
225 out[byte] |= (c & 0x0F) << 4;
226 }
227 }
228 out
229 }
230
231 /// Pack the 3-bit codes TRUE 3-bit: 8 codes → 3 bytes (24 bits) as a
232 /// little-endian bitstream (code k at bits 3k..3k+3). This is 3.125 bpw vs
233 /// the nibble path's 4.125 → ~24% less weight-memory traffic for the matmul,
234 /// raising the decode roofline. Requires `codes.len() % 8 == 0` (true here:
235 /// per-row `inn ∈ {1536, 8960}` is a multiple of 8, and rows are contiguous).
236 /// The GPU kernel reads each octet's 3 bytes, forms a 24-bit word, and
237 /// bit-extracts `(v >> 3k) & 7`. Returns a `Vec<u8>` of length
238 /// `codes.len() / 8 * 3`.
239 pub fn codes_packed_3bit(&self) -> Vec<u8> {
240 let n = self.codes.len();
241 debug_assert_eq!(n % 8, 0, "3-bit packing needs codes.len() % 8 == 0");
242 let mut out = vec![0u8; (n / 8) * 3];
243 for (g, octet) in self.codes.chunks_exact(8).enumerate() {
244 // little-endian 24-bit field: code j at bits 3j..3j+3
245 let mut v: u32 = 0;
246 for (j, &c) in octet.iter().enumerate() {
247 v |= ((c as u32) & 0x7) << (3 * j);
248 }
249 let b = g * 3;
250 out[b] = (v & 0xFF) as u8;
251 out[b + 1] = ((v >> 8) & 0xFF) as u8;
252 out[b + 2] = ((v >> 16) & 0xFF) as u8;
253 }
254 out
255 }
256
257 /// ALIGNED 3-bit packing for the coalesced-uint kernel (`tq_qmatvec3a_bf16`).
258 /// 32 codes → 3 u32 words (96 bits, zero waste = 3.0 bpw for codes). Code `c`
259 /// (0..32 within a block) occupies bits `3c..3c+3` of the little-endian 96-bit
260 /// field spanning the 3 words; the two straddling fields (c=10 at bit 30, c=21
261 /// at bit 63) split across word boundaries — written here, stitched in-kernel.
262 /// Requires `codes.len() % 32 == 0` (true: every row's inn ∈ {512,3584,8960,
263 /// 18944} is a multiple of 32 and rows are contiguous). Returns bytes (3 u32
264 /// per 32-code block, little-endian), length `codes.len()/32*12`.
265 #[allow(dead_code)] // negative result: aligned 3-bit reads were SLOWER than octets
266 pub fn codes_packed_3bit_aligned(&self) -> Vec<u8> {
267 let n = self.codes.len();
268 debug_assert_eq!(n % 32, 0, "aligned 3-bit packing needs codes.len() % 32 == 0");
269 let nblk = n / 32;
270 let mut out = vec![0u8; nblk * 12];
271 for (b, blk) in self.codes.chunks_exact(32).enumerate() {
272 let mut words = [0u32; 3];
273 for (c, &code) in blk.iter().enumerate() {
274 let bit = 3 * c; // 0..96
275 let w = bit / 32; // 0,1,2
276 let off = bit % 32;
277 let v = (code as u64) & 0x7;
278 // place into a 64-bit window starting at word w, then split back.
279 let lo = (v << off) as u32;
280 words[w] |= lo;
281 if off > 29 && w < 2 {
282 words[w + 1] |= (v >> (32 - off)) as u32;
283 }
284 }
285 let base = b * 12;
286 for (wi, word) in words.iter().enumerate() {
287 let wb = base + wi * 4;
288 out[wb] = (word & 0xFF) as u8;
289 out[wb + 1] = ((word >> 8) & 0xFF) as u8;
290 out[wb + 2] = ((word >> 16) & 0xFF) as u8;
291 out[wb + 3] = ((word >> 24) & 0xFF) as u8;
292 }
293 }
294 out
295 }
296}
297
298/// Nearest-centroid quantize via midpoint edges (searchsorted), returns code.
299#[inline]
300fn quantize_one(v: f32, edges: &[f32]) -> u8 {
301 let mut j = 0usize;
302 while j < edges.len() && v > edges[j] {
303 j += 1;
304 }
305 j as u8
306}
307
308/// Pick the rotated-grid width P and whether block-Hadamard is usable.
309/// Block-Hadamard needs `inn` to be a multiple of `d` (so each d-wide sub-block
310/// is an exact power-of-two FWHT with no padding). Otherwise fall back to the
311/// v2 full-row pad-to-power-of-two rotation.
312fn rotation_plan(inn: usize, d: usize, want_block: bool) -> (usize, bool) {
313 if want_block && inn % d == 0 {
314 (inn, true) // P == inn, no padding
315 } else {
316 (inn.next_power_of_two(), false)
317 }
318}
319
320/// The largest power-of-two block size ≤ `max_d` that evenly divides `inn`.
321/// Block-Hadamard requires `d` to be a power of two (per-block FWHT) AND `inn %
322/// d == 0` (no padding). The configured `max_d` (128) works for every width that
323/// is a multiple of 128 (all qwen projections, and most DeepSeek ones). Widths
324/// like DeepSeek-V2-Lite's dense `mlp.down_proj` inn=10944 (= 64·171) are only
325/// 64-divisible, so this drops to d=64 for that matrix while keeping 128
326/// everywhere else. `d` is stored per-weight (`q.d`) and read by the inference
327/// rotate, so the encode/decode transforms always match.
328pub fn effective_block_d(inn: usize, max_d: usize) -> usize {
329 let mut d = max_d.max(1).next_power_of_two();
330 if d > max_d {
331 d >>= 1; // next_power_of_two rounds up; keep ≤ max_d
332 }
333 while d > 1 && inn % d != 0 {
334 d >>= 1;
335 }
336 d.max(1)
337}
338
339/// Rotate one input row into `grid_row` (length p). `block` selects the mode.
340/// In block mode, FWHT each consecutive d-wide chunk independently.
341///
342/// `pub(crate)`: the fast inference path rotates the *activation* x with exactly
343/// this transform (same sgn, same per-d-block FWHT) so that
344/// `⟨x, unrotate(w)⟩ = ⟨rotate(x), w_rotated⟩` and the matmul can read the
345/// compressed rotated codes directly.
346pub(crate) fn rotate_row(
347 src: &[f32],
348 sgn: &[f32],
349 grid_row: &mut [f32],
350 _p: usize, // grid_row already has length p; kept for call-site symmetry
351 d: usize,
352 block: bool,
353) {
354 for v in grid_row.iter_mut() {
355 *v = 0.0;
356 }
357 let inn = src.len();
358 if block {
359 // sgn has length inn; copy*sign then FWHT each d-wide block in place.
360 for k in 0..inn {
361 grid_row[k] = src[k] * sgn[k];
362 }
363 let nblk = inn / d;
364 for b in 0..nblk {
365 fwht_inplace(&mut grid_row[b * d..b * d + d]);
366 }
367 } else {
368 // sgn has length p; pad to p, sign-flip, single full-row FWHT.
369 for k in 0..inn {
370 grid_row[k] = src[k] * sgn[k];
371 }
372 fwht_inplace(grid_row);
373 }
374}
375
376/// Encode a weight matrix `w` (row-major, shape out×inn) data-free.
377pub fn encode(w: &[f32], out: usize, inn: usize, cfg: &TqConfig, codebook: &[f32]) -> TqWeight {
378 // Effective block size: when block-Hadamard is requested, shrink `d` to the
379 // largest power-of-two divisor of `inn` (≤ cfg.d) so block mode is always
380 // usable — d=128 for every 128-divisible width, d=64 for e.g. inn=10944
381 // (DeepSeek-V2-Lite dense down_proj). Stored as `q.d` so inference rotates
382 // identically. Non-block modes keep cfg.d unchanged.
383 let d = if cfg.block_hadamard {
384 effective_block_d(inn, cfg.d)
385 } else {
386 cfg.d
387 };
388 let (p, block) = rotation_plan(inn, d, cfg.block_hadamard);
389 let sgn = signs(p, cfg.seed);
390
391 // Build the rotated grid: per row, sign-flip + (full or block-diagonal) FWHT.
392 let mut grid = vec![0f32; out * p];
393 let mut row_buf = vec![0f32; p];
394 for r in 0..out {
395 let src = &w[r * inn..r * inn + inn];
396 rotate_row(src, &sgn, &mut row_buf, p, d, block);
397 grid[r * p..r * p + p].copy_from_slice(&row_buf);
398 }
399
400 // Outlier split (in rotated space): keep top-k |value| in fp16, zero them.
401 let mut outlier_idx = Vec::new();
402 let mut outlier_val = Vec::new();
403 let k = (cfg.outlier_frac as f64 * grid.len() as f64) as usize;
404 if k > 0 {
405 // Partial selection: find the k largest |grid|. Simple approach — collect
406 // (|v|, idx), select the k-th largest via select_nth_unstable.
407 let mut mags: Vec<(f32, u32)> =
408 grid.iter().enumerate().map(|(i, &v)| (v.abs(), i as u32)).collect();
409 let kth = mags.len() - k;
410 mags.select_nth_unstable_by(kth, |a, b| a.0.partial_cmp(&b.0).unwrap());
411 for &(_, idx) in &mags[kth..] {
412 let i = idx as usize;
413 outlier_idx.push(idx);
414 outlier_val.push(f16::from_f32(grid[i]));
415 grid[i] = 0.0;
416 }
417 }
418
419 // Block-quantize: per block of d (the effective, per-matrix block size bound
420 // above), RMS radius (fp16), normalize, codebook lookup.
421 debug_assert_eq!(grid.len() % d, 0, "out*P must be divisible by d");
422 let nblocks = grid.len() / d;
423 let edges: Vec<f32> = (0..codebook.len() - 1)
424 .map(|j| (codebook[j] + codebook[j + 1]) / 2.0)
425 .collect();
426
427 let mut codes = vec![0u8; grid.len()];
428 let mut radius = Vec::with_capacity(nblocks);
429 for b in 0..nblocks {
430 let blk = &grid[b * d..b * d + d];
431 let mean_sq: f32 = blk.iter().map(|&v| v * v).sum::<f32>() / d as f32;
432 let r = mean_sq.sqrt() + 1e-12;
433 let r16 = f16::from_f32(r);
434 radius.push(r16);
435 // Use the fp16-rounded radius for normalization so decode matches exactly.
436 let r_used = r16.to_f32();
437 let inv = 1.0 / r_used;
438 for (j, &v) in blk.iter().enumerate() {
439 codes[b * d + j] = quantize_one(v * inv, &edges);
440 }
441 }
442
443 TqWeight {
444 out,
445 inn,
446 p,
447 d,
448 bits: cfg.bits,
449 seed: cfg.seed,
450 block_hadamard: block,
451 codes,
452 radius,
453 codebook: codebook.to_vec(),
454 outlier_idx,
455 outlier_val,
456 }
457}
458
459/// Decode the compressed weight back to a dense row-major f32 matrix (out×inn).
460pub fn decode(q: &TqWeight) -> Vec<f32> {
461 let d = q.d;
462 let p = q.p;
463
464 // Reconstruct the rotated grid: codebook[code] * radius (per block).
465 let mut grid = vec![0f32; q.out * p];
466 for (b, &r16) in q.radius.iter().enumerate() {
467 let r = r16.to_f32();
468 for j in 0..d {
469 let idx = b * d + j;
470 grid[idx] = q.codebook[q.codes[idx] as usize] * r;
471 }
472 }
473
474 // Restore outliers (fp16) into the rotated grid.
475 for (slot, &idx) in q.outlier_idx.iter().enumerate() {
476 grid[idx as usize] = q.outlier_val[slot].to_f32();
477 }
478
479 // Inverse rotation: per row, FWHT (self-inverse) then × signs, crop to inn.
480 // Must mirror the same mode (full pad-to-pow2 vs block-diagonal) used to encode.
481 let sgn = signs(p, q.seed);
482 let mut out = vec![0f32; q.out * q.inn];
483 let mut row_buf = vec![0f32; p];
484 for r in 0..q.out {
485 row_buf.copy_from_slice(&grid[r * p..r * p + p]);
486 if q.block_hadamard {
487 let nblk = p / d; // p == inn here
488 for b in 0..nblk {
489 fwht_inplace(&mut row_buf[b * d..b * d + d]);
490 }
491 } else {
492 fwht_inplace(&mut row_buf);
493 }
494 for k in 0..q.inn {
495 out[r * q.inn + k] = row_buf[k] * sgn[k];
496 }
497 }
498 out
499}
500
501/// Relative Frobenius error ‖W − Ŵ‖ / ‖W‖ — the recon-quality metric from the POC.
502pub fn relative_fro(w: &[f32], wq: &[f32]) -> f64 {
503 let mut num = 0f64;
504 let mut den = 0f64;
505 for i in 0..w.len() {
506 let dv = (w[i] - wq[i]) as f64;
507 num += dv * dv;
508 den += (w[i] as f64) * (w[i] as f64);
509 }
510 (num.sqrt()) / (den.sqrt().max(1e-30))
511}
512
513#[cfg(test)]
514mod tests {
515 use super::*;
516
517 #[test]
518 fn packed_3bit_roundtrips() {
519 // codes_packed_3bit must reproduce every code under the GPU kernel's
520 // unpack (8 codes per 24-bit little-endian octet, code j at bits 3j..3j+3).
521 let (out, inn) = (4usize, 256usize); // inn % 8 == 0
522 let mut st = 7u64;
523 let mut nf = || {
524 st = st.wrapping_mul(6364136223846793005).wrapping_add(1);
525 ((st >> 11) as f64 / (1u64 << 53) as f64 - 0.5) as f32
526 };
527 let w: Vec<f32> = (0..out * inn).map(|_| nf()).collect();
528 let cfg = TqConfig { outlier_frac: 0.0, block_hadamard: true, ..TqConfig::default() };
529 let q = encode(&w, out, inn, &cfg, &LLOYD_MAX_3BIT);
530 let packed = q.codes_packed_3bit();
531 assert_eq!(packed.len(), q.codes.len() / 8 * 3);
532 // unpack exactly as tq_qmatvec3_f32 does
533 for (g, chunk) in q.codes.chunks_exact(8).enumerate() {
534 let bb = g * 3;
535 let v = (packed[bb] as u32) | ((packed[bb + 1] as u32) << 8) | ((packed[bb + 2] as u32) << 16);
536 for (j, &c) in chunk.iter().enumerate() {
537 let dec = ((v >> (3 * j)) & 0x7) as u8;
538 assert_eq!(dec, c, "3-bit unpack mismatch at octet {g} code {j}");
539 assert!(c < 8, "code out of 3-bit range");
540 }
541 }
542 }
543
544 #[test]
545 fn fwht_self_inverse() {
546 let mut x = vec![1.0f32, -2.0, 3.0, 0.5, -1.5, 2.0, -0.25, 4.0];
547 let orig = x.clone();
548 fwht_inplace(&mut x);
549 fwht_inplace(&mut x);
550 for (a, b) in x.iter().zip(orig.iter()) {
551 assert!((a - b).abs() < 1e-4, "FWHT not self-inverse: {a} vs {b}");
552 }
553 }
554
555 #[test]
556 fn activation_rotation_matches_dense_matmul() {
557 // The fast path computes y[o] = Σ_k rotate(x)[k] * Wr[o,k] where
558 // Wr[o,k] = codebook[codes[o*inn+k]] * radius(block) and
559 // rotate(x) = blockFWHT(x ∘ sgn). This must equal the dense
560 // y[o] = Σ_k x[k] * decode(W)[o,k]. Verify on a block-Hadamard weight.
561 let (out, inn) = (64usize, 256usize); // inn % d(128)==0
562 let mut state = 99u64;
563 let mut nextf = || {
564 state = state.wrapping_mul(6364136223846793005).wrapping_add(1);
565 ((state >> 11) as f64 / (1u64 << 53) as f64 - 0.5) as f32
566 };
567 let w: Vec<f32> = (0..out * inn).map(|_| nextf()).collect();
568 let x: Vec<f32> = (0..inn).map(|_| nextf()).collect();
569
570 let cfg = TqConfig { outlier_frac: 0.0, block_hadamard: true, ..TqConfig::default() };
571 let q = encode(&w, out, inn, &cfg, &LLOYD_MAX_3BIT);
572 assert!(q.block_hadamard);
573 let wq = decode(&q); // dense reconstructed weight (out×inn)
574
575 // dense reference: y_dense[o] = Σ_k x[k] * wq[o,k]
576 let mut y_dense = vec![0f32; out];
577 for o in 0..out {
578 let mut acc = 0f32;
579 for k in 0..inn {
580 acc += x[k] * wq[o * inn + k];
581 }
582 y_dense[o] = acc;
583 }
584
585 // fast path: rotate x, then dot with the reconstructed rotated codes.
586 let sgn = signs(q.p, q.seed);
587 let mut xr = vec![0f32; q.p];
588 rotate_row(&x, &sgn, &mut xr, q.p, q.d, true);
589 let mut y_fast = vec![0f32; out];
590 for o in 0..out {
591 let mut acc = 0f32;
592 for k in 0..inn {
593 let idx = o * inn + k;
594 let r = q.radius[idx / q.d].to_f32();
595 let wr = q.codebook[q.codes[idx] as usize] * r;
596 acc += xr[k] * wr;
597 }
598 y_fast[o] = acc;
599 }
600
601 let mut max_abs = 0f32;
602 for o in 0..out {
603 max_abs = max_abs.max((y_dense[o] - y_fast[o]).abs());
604 }
605 assert!(
606 max_abs < 1e-3,
607 "activation-rotation identity broken: max |Δ| = {max_abs}"
608 );
609 }
610
611 #[test]
612 fn roundtrip_gaussian_is_reasonable() {
613 // A Gaussian matrix should reconstruct with relFro well under 0.2 at 3 bits.
614 let (out, inn) = (256usize, 300usize);
615 let mut state = 12345u64;
616 let mut nextf = || {
617 state = state.wrapping_mul(6364136223846793005).wrapping_add(1);
618 ((state >> 11) as f64 / (1u64 << 53) as f64) as f32
619 };
620 let mut w = vec![0f32; out * inn];
621 for chunk in w.chunks_mut(2) {
622 let u1 = (nextf() as f64).max(1e-12);
623 let u2 = nextf() as f64;
624 let r = (-2.0 * u1.ln()).sqrt();
625 chunk[0] = (r * (std::f64::consts::TAU * u2).cos()) as f32;
626 if chunk.len() > 1 {
627 chunk[1] = (r * (std::f64::consts::TAU * u2).sin()) as f32;
628 }
629 }
630 let cfg = TqConfig::default();
631 let q = encode(&w, out, inn, &cfg, &LLOYD_MAX_3BIT);
632 let wq = decode(&q);
633 let rf = relative_fro(&w, &wq);
634 assert!(rf < 0.2, "relFro too high: {rf}");
635 }
636}