nx_vq.nx source
↩ module page · 39 lines · 1713 B
1// nx_vq.nx -- VECTOR QUANTIZATION, the first rung of the sovereign neural-audio moonshot. Instead of scalar-quantising
2// each LPC reflection coefficient (D coeffs x 8 bits), VQ maps the WHOLE coefficient vector to the nearest entry in a
3// learned codebook and transmits one small index (log2(K) bits). This is the exact classical precursor to the residual
4// vector quant(RVQ) codebooks inside SoundStream / Lyra-v2 -- the lever that takes our DRED redundancy overhead from
5// ~44 kb/s (scalar i8) toward the 12-32 kb/s neural target. The codebook QUALITY (coverage of the space) is the training
6// problem whose ceiling is the neural net; the VQ MECHANISM here is exact + integer. license_tier: ORIGINAL
7
8// squared L2 distance between vector v[D] and codebook entry k (entries laid out cb[k*D + i])
9func vq_dist2(v: *i64, cb: *i64, k: i64, D: i64) -> i64 {
10 var s: i64 = 0
11 var i: i64 = 0
12 while i < D { let d: i64 = v[i] - cb[k*D + i]; s = s + d*d; i = i + 1 }
13 return s
14}
15// encode: index of the nearest codebook entry (0..K-1)
16func vq_encode(v: *i64, cb: *i64, K: i64, D: i64) -> i64 {
17 var best: i64 = 0
18 var bestd: i64 = vq_dist2(v, cb, 0, D)
19 var k: i64 = 1
20 while k < K {
21 let dd: i64 = vq_dist2(v, cb, k, D)
22 if dd < bestd { bestd = dd; best = k }
23 k = k + 1
24 }
25 return best
26}
27// decode: copy codebook entry k into out[D]
28func vq_decode(k: i64, cb: *i64, D: i64, out: *i64) -> i64 {
29 var i: i64 = 0
30 while i < D { out[i] = cb[k*D + i]; i = i + 1 }
31 return 0
32}
33// bits to index a K-entry codebook (ceil log2 K)
34func vq_index_bits(K: i64) -> i64 {
35 var b: i64 = 0
36 var x: i64 = 1
37 while x < K { x = x * 2; b = b + 1 }
38 return b
39}