interplane.Get Omega
Read in your language

aienux

Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.

Brought by drakestapleton

branch main Branches Tags History

aienux / crates / aienos-infer / src / quant.rs

279 lines · 10364 bytes Raw Blame History
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! ggml block dequantizers (scalar reference implementations).
17//!
18//! Formulas follow ggml's `dequantize_row_q4_K` / `dequantize_row_q6_K`
19//! (ggml-quants.c). Both formats pack 256 weights per super-block.
20
21use crate::gguf::GgmlType;
22use crate::half::f16_to_f32;
23
24/// Weights per K-quant super-block.
25pub const QK_K: usize = 256;
26/// Bytes per Q4_K block: f16 d, f16 dmin, 12 bytes scales/mins, 128 bytes nibbles.
27pub const Q4K_BYTES: usize = 144;
28/// Bytes per Q6_K block: 128 ql, 64 qh, 16 i8 scales, f16 d.
29pub const Q6K_BYTES: usize = 210;
30
31/// Reasons a dequantization request is refused.
32#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33pub enum QuantError {
34 /// Type has no dequantizer here.
35 Unsupported(GgmlType),
36 /// Source length is not the whole number of blocks that `out` needs.
37 BadLength,
38}
39
40fn rd_f16(b: &[u8], at: usize) -> f32 {
41 f16_to_f32(u16::from_le_bytes([b[at], b[at + 1]]))
42}
43
44/// 6-bit scale and min for sub-block `j` (0..8) from the 12 packed bytes.
45pub(crate) fn scale_min_k4(j: usize, q: &[u8]) -> (u8, u8) {
46 if j < 4 {
47 (q[j] & 63, q[j + 4] & 63)
48 } else {
49 (
50 (q[j + 4] & 0x0f) | ((q[j - 4] >> 6) << 4),
51 (q[j + 4] >> 4) | ((q[j] >> 6) << 4),
52 )
53 }
54}
55
56/// Dequantize one Q4_K block (144 bytes) into 256 floats.
57pub fn dequant_q4k_block(block: &[u8; Q4K_BYTES], out: &mut [f32; QK_K]) {
58 let d = rd_f16(block, 0);
59 let dmin = rd_f16(block, 2);
60 let scales = &block[4..16];
61 let qs = &block[16..144];
62 for j in 0..4 {
63 let (sc1, m1) = scale_min_k4(2 * j, scales);
64 let (sc2, m2) = scale_min_k4(2 * j + 1, scales);
65 let (d1, mn1) = (d * sc1 as f32, dmin * m1 as f32);
66 let (d2, mn2) = (d * sc2 as f32, dmin * m2 as f32);
67 let q = &qs[32 * j..32 * j + 32];
68 let o = &mut out[64 * j..64 * j + 64];
69 for l in 0..32 {
70 o[l] = d1 * (q[l] & 0x0f) as f32 - mn1;
71 o[l + 32] = d2 * (q[l] >> 4) as f32 - mn2;
72 }
73 }
74}
75
76/// Dequantize one Q6_K block (210 bytes) into 256 floats.
77pub fn dequant_q6k_block(block: &[u8; Q6K_BYTES], out: &mut [f32; QK_K]) {
78 let d = rd_f16(block, 208);
79 for half in 0..2 {
80 let ql = &block[64 * half..64 * half + 64];
81 let qh = &block[128 + 32 * half..128 + 32 * half + 32];
82 let sc = &block[192 + 8 * half..192 + 8 * half + 8];
83 let o = &mut out[128 * half..128 * half + 128];
84 for l in 0..32 {
85 let is = l / 16;
86 let h = qh[l];
87 let q1 = ((ql[l] & 0x0f) | ((h & 3) << 4)) as i32 - 32;
88 let q2 = ((ql[l + 32] & 0x0f) | (((h >> 2) & 3) << 4)) as i32 - 32;
89 let q3 = ((ql[l] >> 4) | (((h >> 4) & 3) << 4)) as i32 - 32;
90 let q4 = ((ql[l + 32] >> 4) | (((h >> 6) & 3) << 4)) as i32 - 32;
91 o[l] = d * (sc[is] as i8) as f32 * q1 as f32;
92 o[l + 32] = d * (sc[is + 2] as i8) as f32 * q2 as f32;
93 o[l + 64] = d * (sc[is + 4] as i8) as f32 * q3 as f32;
94 o[l + 96] = d * (sc[is + 6] as i8) as f32 * q4 as f32;
95 }
96 }
97}
98
99fn as_block<const N: usize>(b: &[u8]) -> &[u8; N] {
100 // Callers pass chunks_exact(N) slices, so the length is always N.
101 b.try_into().expect("chunk length is N")
102}
103
104/// Dot product of one Q4_K block with 256 f32 activations (dequantize, then
105/// accumulate in f32; scalar reference, not bit-identical to ggml's q8 path).
106pub fn dot_q4k_f32(block: &[u8; Q4K_BYTES], x: &[f32; QK_K]) -> f32 {
107 let mut w = [0f32; QK_K];
108 dequant_q4k_block(block, &mut w);
109 w.iter().zip(x).map(|(a, b)| a * b).sum()
110}
111
112/// Dot product of one Q6_K block with 256 f32 activations.
113pub fn dot_q6k_f32(block: &[u8; Q6K_BYTES], x: &[f32; QK_K]) -> f32 {
114 let mut w = [0f32; QK_K];
115 dequant_q6k_block(block, &mut w);
116 w.iter().zip(x).map(|(a, b)| a * b).sum()
117}
118
119/// Dot of a whole quantized row (`src`, `x.len()` weights) with `x`.
120pub fn dot_row(ty: GgmlType, src: &[u8], x: &[f32]) -> Result<f32, QuantError> {
121 let (bw, bb) = ty.block();
122 if !matches!(ty, GgmlType::Q4K | GgmlType::Q6K) {
123 return Err(QuantError::Unsupported(ty));
124 }
125 if x.len() % bw != 0 || src.len() != x.len() / bw * bb {
126 return Err(QuantError::BadLength);
127 }
128 let mut acc = 0f32;
129 for (blk, xs) in src.chunks_exact(bb).zip(x.chunks_exact(QK_K)) {
130 let xs: &[f32; QK_K] = xs.try_into().expect("chunk is QK_K");
131 acc += if ty == GgmlType::Q4K {
132 dot_q4k_f32(as_block(blk), xs)
133 } else {
134 dot_q6k_f32(as_block(blk), xs)
135 };
136 }
137 Ok(acc)
138}
139
140/// Dequantize `out.len()` weights of type `ty` from `src` (whole blocks).
141pub fn dequantize(ty: GgmlType, src: &[u8], out: &mut [f32]) -> Result<(), QuantError> {
142 let (bw, bb) = ty.block();
143 if out.len() % bw != 0 || src.len() != out.len() / bw * bb {
144 return Err(QuantError::BadLength);
145 }
146 match ty {
147 GgmlType::Q4K => {
148 for (blk, o) in src.chunks_exact(bb).zip(out.chunks_exact_mut(QK_K)) {
149 dequant_q4k_block(as_block(blk), o.try_into().expect("chunk is QK_K"));
150 }
151 }
152 GgmlType::Q6K => {
153 for (blk, o) in src.chunks_exact(bb).zip(out.chunks_exact_mut(QK_K)) {
154 dequant_q6k_block(as_block(blk), o.try_into().expect("chunk is QK_K"));
155 }
156 }
157 other => {
158 if !crate::gguf::plain_to_f32(other, src, out) {
159 return Err(QuantError::Unsupported(other));
160 }
161 }
162 }
163 Ok(())
164}
165
166#[cfg(test)]
167mod tests {
168 use super::*;
169
170 const ONE: [u8; 2] = [0x00, 0x3c]; // f16 1.0
171
172 #[test]
173 fn q4k_hand_block() {
174 // d=1, dmin=1. Sub-block j has scale j+1 and min j (all < 16 so they
175 // sit in the plain low 6 bits of bytes 0..8). Nibble pattern: low
176 // nibble = l%16, high nibble = 15 - l%16.
177 let mut b = [0u8; Q4K_BYTES];
178 b[0..2].copy_from_slice(&ONE);
179 b[2..4].copy_from_slice(&ONE);
180 for j in 0..4 {
181 b[4 + j] = (j + 1) as u8; // scales 1..4 for sub-blocks 0..4
182 b[8 + j] = j as u8; // mins 0..3
183 }
184 // sub-blocks 4..8: low nibble of bytes 8..12 = scale, high = min, and
185 // the top two bits of bytes 0..4 / 4..8 are 0 so no extension.
186 for j in 4..8 {
187 b[8 + j] = ((j + 1) as u8) | ((j as u8) << 4);
188 }
189 for l in 0..128 {
190 let lo = (l % 16) as u8;
191 b[16 + l] = lo | ((15 - lo) << 4);
192 }
193 let mut out = [0f32; QK_K];
194 dequant_q4k_block(&b, &mut out);
195 for sb in 0..8 {
196 let j = sb / 2;
197 let (sc, mn) = (sb + 1, sb);
198 for l in 0..32 {
199 let lo = (l % 16) as f32;
200 let q = if sb % 2 == 0 { lo } else { 15.0 - lo };
201 let expect = sc as f32 * q - mn as f32;
202 assert_eq!(out[32 * sb + l], expect, "sb {sb} l {l} (j {j})");
203 }
204 }
205 }
206
207 #[test]
208 fn q4k_scale_extension_bits() {
209 // Sub-block 4: scale = 0xf | (3 << 4) = 63 (byte 8 low nibble + byte 0 >> 6);
210 // min = 0x2 | (2 << 4) = 34 (byte 8 high nibble + byte 4 >> 6).
211 let mut b = [0u8; Q4K_BYTES];
212 b[0..2].copy_from_slice(&ONE);
213 b[2..4].copy_from_slice(&ONE);
214 b[4] = 3 << 6; // byte 0 of scales: top bits -> scale high of sb4
215 b[8] = 2 << 6; // byte 4 of scales: top bits -> min high of sb4
216 b[12] = 0x0f | (0x2 << 4);
217 for q in b[16..].iter_mut() {
218 *q = 0x11;
219 }
220 let mut out = [0f32; QK_K];
221 dequant_q4k_block(&b, &mut out);
222 // sb4 is the low half of j=2 qs; nibble 1 -> 63*1 - 42.
223 assert_eq!(out[128], 63.0 - 34.0);
224 // sb0 has scale 0, min 0 -> exactly 0.
225 assert_eq!(out[0], 0.0);
226 }
227
228 #[test]
229 fn q6k_hand_block() {
230 // d=1, all scales 1, ql nibbles = 0x0, qh = 0 -> q = -32 everywhere
231 // for low nibbles; set specific positions to check the bit layout.
232 let mut b = [0u8; Q6K_BYTES];
233 b[208..210].copy_from_slice(&ONE);
234 for i in 0..16 {
235 b[192 + i] = 1;
236 }
237 let mut out = [0f32; QK_K];
238 dequant_q6k_block(&b, &mut out);
239 assert!(out.iter().all(|&v| v == -32.0));
240 // l=0 of the first half: ql[0]=0x5a, qh[0]=0b11_10_01_00.
241 b[0] = 0x5a;
242 b[128] = 0b1110_0100;
243 dequant_q6k_block(&b, &mut out);
244 assert_eq!(out[0], 0xa as f32 - 32.0); // q1
245 assert_eq!(out[64], ((0x5) | (2 << 4)) as f32 - 32.0); // q3: qh bits 4..6 = 2
246 assert_eq!(out[32], 16.0 - 32.0); // q2: low nibble 0, qh bits 2..4 = 1
247 assert_eq!(out[96], 48.0 - 32.0); // q4: low nibble of ql[32]=0, qh bits 6..8 = 3
248 }
249
250 #[test]
251 fn q6k_scales_are_signed_and_per_16() {
252 let mut b = [0u8; Q6K_BYTES];
253 b[208..210].copy_from_slice(&ONE);
254 for i in 0..16 {
255 b[192 + i] = (i as i8 - 8) as u8;
256 }
257 // ql/qh zero -> q=-32; weight p has scale index p/16.
258 let mut out = [0f32; QK_K];
259 dequant_q6k_block(&b, &mut out);
260 for p in 0..QK_K {
261 assert_eq!(out[p], (p / 16) as f32 * -32.0 + 8.0 * 32.0, "p {p}");
262 }
263 }
264
265 #[test]
266 fn length_checks() {
267 let mut out = [0f32; QK_K];
268 assert_eq!(
269 dequantize(GgmlType::Q4K, &[0u8; 143], &mut out),
270 Err(QuantError::BadLength)
271 );
272 assert_eq!(
273 dequantize(GgmlType::Q5K, &[0u8; 176], &mut out),
274 Err(QuantError::Unsupported(GgmlType::Q5K))
275 );
276 let x = [1f32; QK_K];
277 assert_eq!(dot_row(GgmlType::Q4K, &[0u8; Q4K_BYTES], &x), Ok(0.0));
278 }
279}