STRA-102 port Q6_K and Q2_0 preparation to Rust

This commit is contained in:
Pavlo Ratushnyi
2026-10-07 22:04:08 +02:00
parent 47ab90c7e0
commit 4fa9d307fe
7 changed files with 914 additions and 2 deletions
+211
View File
@@ -853,4 +853,215 @@ mod tests {
}
}
}
// The field generator does not call either Rust decoder or its unpack helper.
fn synthetic_q6_q2_block(kind: u32, bits: u16, pattern: u32) -> Vec<u8> {
if kind == 42 {
let mut block = vec![0u8; 18];
block[..2].copy_from_slice(&bits.to_le_bytes());
for (lane, byte) in block[2..].iter_mut().enumerate() {
for field in 0..4 {
*byte |= (((pattern as usize + lane + field) & 3) as u8) << (field * 2);
}
}
block
} else {
assert_eq!(kind, 14);
let mut block = vec![0u8; 210];
block[208..].copy_from_slice(&bits.to_le_bytes());
for scale in 0..16 {
block[192 + scale] = (pattern >> 6) as u8;
block[192 + scale] = block[192 + scale].wrapping_add((scale * 17) as u8);
}
for half in 0..2 {
for quadrant in 0..4 {
for lane in 0..32 {
let position = half * 128 + quadrant * 32 + lane;
let code = ((pattern as usize + position * 13) & 63) as u8;
let low_index = half * 64 + (quadrant % 2) * 32 + lane;
block[low_index] |= (code & 15) << ((quadrant / 2) * 4);
block[128 + half * 32 + lane] |= (code >> 4) << (quadrant * 2);
}
}
}
block
}
}
fn rust_q6_q2_into(kind: u32, source: &[u8], output: &mut [f32]) -> Result<(), String> {
if kind == 14 {
leleka_quant_core::q6_k::decode_into(source, output)
} else {
assert_eq!(kind, 42);
leleka_quant_core::q2_0::decode_into(source, output)
}
}
fn assert_q6_q2_c_bits(kind: u32, source: &[u8], finite: bool) {
let (elements, bytes) = gguf::block_geometry(kind).unwrap();
let mut expected = vec![0.0; source.len() / bytes as usize * elements as usize];
let mut actual = vec![0.0; expected.len()];
decode_into(kind, source, &mut expected).unwrap();
rust_q6_q2_into(kind, source, &mut actual).unwrap();
for (position, (actual, expected)) in actual.iter().zip(&expected).enumerate() {
if finite {
assert!(actual.is_finite() && expected.is_finite());
}
if expected.is_nan() {
assert!(actual.is_nan(), "kind {kind} position {position}");
} else {
assert_eq!(
actual.to_bits(),
expected.to_bits(),
"kind {kind} position {position}"
);
}
}
}
#[test]
fn pinned_ggml_q6_q2_all_finite_fp16_scales_match_exact_c_bits() {
let mut scales = 0;
for bits in 0..=u16::MAX {
if bits & 0x7c00 == 0x7c00 {
continue;
}
assert_q6_q2_c_bits(14, &synthetic_q6_q2_block(14, bits, u32::from(bits)), true);
// Four blocks exercise every Q2 code at every consecutive output position.
for pattern in 0..4 {
assert_q6_q2_c_bits(42, &synthetic_q6_q2_block(42, bits, pattern), true);
}
scales += 1;
}
assert_eq!(scales, 63_488);
}
#[test]
fn pinned_ggml_q6_signed_subscale_quant_pairs_cover_every_output_position() {
let mut pairs = vec![vec![false; 256 * 64]; 256];
for pattern in 0..16_384u32 {
let block = synthetic_q6_q2_block(14, 0xb555, pattern);
assert_q6_q2_c_bits(14, &block, true);
for (position, seen) in pairs.iter_mut().enumerate() {
let half = position / 128;
let quadrant = position % 128 / 32;
let lane = position % 32;
let low = block[half * 64 + (quadrant % 2) * 32 + lane];
let high = block[128 + half * 32 + lane];
let code =
((low >> ((quadrant / 2) * 4)) & 15) | (((high >> (quadrant * 2)) & 3) << 4);
let scale = block[192 + half * 8 + quadrant * 2 + lane / 16];
seen[usize::from(scale) * 64 + usize::from(code)] = true;
}
}
for (position, seen) in pairs.iter().enumerate() {
assert!(
seen.iter().all(|value| *value),
"half/quadrant/lane position {position}"
);
}
}
#[test]
fn pinned_ggml_q6_q2_raw_fields_cover_all_bytes_and_q2_consecutive_codes() {
for kind in [14, 42] {
let (elements, bytes) = gguf::block_geometry(kind).unwrap();
let fields = if kind == 14 { 208 } else { 16 };
let start = if kind == 14 { 0 } else { 2 };
let mut raw_seen = vec![[false; 256]; fields];
let mut codes_seen = vec![[false; 4]; 64];
for pattern in 0..=u8::MAX {
let mut block = vec![0u8; bytes as usize];
let header = if kind == 14 { 208 } else { 0 };
block[header..header + 2].copy_from_slice(&0x3555u16.to_le_bytes());
for field in 0..fields {
let byte = pattern
.wrapping_mul((field * 2 + 1) as u8)
.rotate_left((field % 8) as u32)
.wrapping_add((field * 19) as u8);
block[start + field] = byte;
raw_seen[field][usize::from(byte)] = true;
}
if kind == 42 {
for (position, seen) in codes_seen.iter_mut().enumerate() {
let code = (block[2 + position / 4] >> ((position % 4) * 2)) & 3;
seen[usize::from(code)] = true;
}
}
assert_q6_q2_c_bits(kind, &block, true);
}
assert!(raw_seen.iter().all(|seen| seen.iter().all(|value| *value)));
if kind == 42 {
assert_eq!(elements, 64);
assert!(
codes_seen
.iter()
.all(|seen| seen.iter().all(|value| *value))
);
}
}
}
#[test]
fn pinned_ggml_q6_q2_all_nonfinite_headers_and_zero_factors_preserve_c_values() {
let mut headers = 0;
for bits in 0..=u16::MAX {
if bits & 0x7c00 != 0x7c00 {
continue;
}
let mut block = synthetic_q6_q2_block(14, bits, u32::from(bits));
assert_q6_q2_c_bits(14, &block, false);
// Zero subscale and zero signed quant independently reach Inf*zero.
block[192..208].fill(0);
assert_q6_q2_c_bits(14, &block, false);
block[192..208].fill(1);
block[..128].fill(0);
block[128..192].fill(0xaa); // each high field 2, low 0 -> signed quant 0
assert_q6_q2_c_bits(14, &block, false);
for pattern in 0..4 {
assert_q6_q2_c_bits(42, &synthetic_q6_q2_block(42, bits, pattern), false);
}
headers += 1;
}
assert_eq!(headers, 2048);
}
#[test]
fn pinned_ggml_q6_q2_aligned_unaligned_bulk_and_shape_sentinels_match() {
let edges = [
0x0000u16, 0x8000, 0x0001, 0x8001, 0x03ff, 0x83ff, 0x0400, 0x8400, 0x3555, 0xb555,
0x3800, 0xb800, 0x3c00, 0xbc00, 0x7bff, 0xfbff,
];
for kind in [14, 42] {
let (elements, bytes) = gguf::block_geometry(kind).unwrap();
let bytes = bytes as usize;
for unaligned in [false, true] {
let mut storage = vec![0; edges.len() * bytes + 16];
let start = storage.as_ptr().align_offset(16) + usize::from(unaligned);
let source = &mut storage[start..start + edges.len() * bytes];
assert_eq!(
source.as_ptr().align_offset(16),
if unaligned { 15 } else { 0 }
);
for (number, bits) in edges.into_iter().enumerate() {
source[number * bytes..(number + 1) * bytes]
.copy_from_slice(&synthetic_q6_q2_block(kind, bits, number as u32 * 257));
}
assert_q6_q2_c_bits(kind, source, true);
let outputs = edges.len() * elements as usize;
for (input_len, output_len) in [
(0, outputs),
(source.len() - 1, outputs),
(source.len(), outputs - 1),
(source.len(), outputs + 1),
] {
let mut output = vec![123.0; output_len];
assert!(rust_q6_q2_into(kind, &source[..input_len], &mut output).is_err());
assert!(output.iter().all(|value| *value == 123.0));
assert!(decode_into(kind, &source[..input_len], &mut output).is_err());
assert!(output.iter().all(|value| *value == 123.0));
}
}
}
}
}
+207 -1
View File
@@ -3,7 +3,7 @@
use std::io::{Read, Seek, SeekFrom};
use leleka_quant_core::{iq4_nl, iq4_xs, q4_k, q5_k, q8_0};
use leleka_quant_core::{iq4_nl, iq4_xs, q2_0, q4_k, q5_k, q6_k, q8_0};
use crate::{ggml_bridge, gguf, iq3_s, kar_codec};
@@ -29,6 +29,8 @@ where
8 => Some((q8_0::BLOCK_ELEMENTS, q8_0::BLOCK_BYTES, "Q8_0")),
12 => Some((q4_k::BLOCK_ELEMENTS, q4_k::BLOCK_BYTES, "Q4_K")),
13 => Some((q5_k::BLOCK_ELEMENTS, q5_k::BLOCK_BYTES, "Q5_K")),
14 => Some((q6_k::BLOCK_ELEMENTS, q6_k::BLOCK_BYTES, "Q6_K")),
42 => Some((q2_0::BLOCK_ELEMENTS, q2_0::BLOCK_BYTES, "Q2_0")),
20 => Some((iq4_nl::BLOCK_ELEMENTS, iq4_nl::BLOCK_BYTES, "IQ4_NL")),
23 => Some((iq4_xs::BLOCK_ELEMENTS, iq4_xs::BLOCK_BYTES, "IQ4_XS")),
_ => None,
@@ -101,6 +103,22 @@ where
}
callback(source, &derived)?;
}
14 => {
for block in source.as_chunks::<{ q6_k::BLOCK_BYTES }>().0 {
for value in q6_k::decode_block(block)? {
derived.extend_from_slice(&value.to_le_bytes());
}
}
callback(source, &derived)?;
}
42 => {
for block in source.as_chunks::<{ q2_0::BLOCK_BYTES }>().0 {
for value in q2_0::decode_block(block)? {
derived.extend_from_slice(&value.to_le_bytes());
}
}
callback(source, &derived)?;
}
20 => {
for block in source.as_chunks::<{ iq4_nl::BLOCK_BYTES }>().0 {
for value in iq4_nl::decode_block(block)? {
@@ -702,4 +720,192 @@ mod tests {
}
}
}
#[test]
fn q6_q2_streams_preserve_bounded_c_bytes_offsets_receipts_and_failure_semantics() {
let edges = [
0x0000u16, 0x8000, 0x0001, 0x83ff, 0x0400, 0x3555, 0xbc00, 0x7bff,
];
for kind in [14, 42] {
let (elements, bytes) = gguf::block_geometry(kind).unwrap();
let bytes = bytes as usize;
let per_chunk = SOURCE_CHUNK_BYTES / bytes;
let blocks = per_chunk + 17;
let prefix = 11;
let mut source = vec![0xa5; prefix];
for number in 0..blocks {
let mut block = vec![0u8; bytes];
for (position, byte) in block.iter_mut().enumerate() {
*byte = (number * 17 + position * 29) as u8;
}
let header = if kind == 14 { 208 } else { 0 };
block[header..header + 2]
.copy_from_slice(&edges[number % edges.len()].to_le_bytes());
source.extend_from_slice(&block);
}
let requested = blocks * bytes;
source.extend_from_slice(&[0x5a; 19]);
let mut cursor = Cursor::new(&source);
let mut consumed = 0;
let mut chunks = Vec::new();
let receipt = visit(
&mut cursor,
prefix as u64,
kind,
requested as u64,
|raw, derived| {
assert!(raw.len() <= SOURCE_CHUNK_BYTES);
assert_eq!(
raw,
&source[prefix + consumed..prefix + consumed + raw.len()]
);
let mut oracle = vec![0.0; raw.len() / bytes * elements as usize];
ggml_bridge::decode_into(kind, raw, &mut oracle).unwrap();
let expected: Vec<u8> = oracle
.iter()
.flat_map(|value| value.to_le_bytes())
.collect();
assert_eq!(derived, expected, "kind {kind}");
assert!(derived.len() <= per_chunk * elements as usize * 4);
chunks.push((raw.len(), derived.len()));
consumed += raw.len();
Ok(())
},
)
.unwrap();
assert_eq!(
chunks,
[
(per_chunk * bytes, per_chunk * elements as usize * 4),
(17 * bytes, 17 * elements as usize * 4)
]
);
assert_eq!(consumed, requested);
assert_eq!(receipt, blocks as u64 * elements * 4);
assert_eq!(cursor.position(), (prefix + requested) as u64);
for malformed in [0, 1, bytes - 1, bytes + 1] {
let mut cursor = Cursor::new(&source);
cursor.set_position(7);
let mut calls = 0;
assert!(
visit(
&mut cursor,
prefix as u64,
kind,
malformed as u64,
|_, _| {
calls += 1;
Ok(())
}
)
.is_err()
);
assert_eq!(calls, 0);
assert_eq!(cursor.position(), 7);
}
for delivered in [0, 1] {
let available = delivered * per_chunk * bytes + bytes - 1;
let required = delivered * per_chunk * bytes + bytes;
let mut calls = 0;
assert!(
visit(
&mut Cursor::new(&source[..prefix + available]),
prefix as u64,
kind,
required as u64,
|raw, derived| {
calls += 1;
assert_eq!(raw.len(), per_chunk * bytes);
assert_eq!(derived.len(), per_chunk * elements as usize * 4);
Ok(())
}
)
.is_err()
);
assert_eq!(calls, delivered);
}
for fail_on in [1, 2] {
let mut cursor = Cursor::new(&source);
let mut calls = 0;
let error = visit(
&mut cursor,
prefix as u64,
kind,
requested as u64,
|_, _| {
calls += 1;
if calls == fail_on {
Err("owned callback abort".into())
} else {
Ok(())
}
},
)
.unwrap_err();
assert_eq!(error, "owned callback abort");
assert_eq!(calls, fail_on);
assert_eq!(
cursor.position(),
(prefix
+ if fail_on == 1 {
per_chunk * bytes
} else {
requested
}) as u64
);
}
}
}
#[test]
fn q6_q2_streams_preserve_nonfinite_headers_and_zero_factors() {
for kind in [14, 42] {
let (elements, bytes) = gguf::block_geometry(kind).unwrap();
for bits in [
0x0000u16, 0x8000, 0x7c00, 0xfc00, 0x7c01, 0xfc01, 0x7e00, 0xfe00,
] {
for variant in 0..3 {
let mut block = vec![0u8; bytes as usize];
for (position, byte) in block.iter_mut().enumerate() {
*byte = (position * 29 + 17) as u8;
}
if kind == 14 {
if variant == 1 {
block[192..208].fill(0);
}
if variant == 2 {
block[..128].fill(0);
block[128..192].fill(0xaa);
}
} else if variant != 0 {
block[2..].fill(if variant == 1 { 0x55 } else { 0 });
}
let header = if kind == 14 { 208 } else { 0 };
block[header..header + 2].copy_from_slice(&bits.to_le_bytes());
let mut oracle = vec![0.0; elements as usize];
ggml_bridge::decode_into(kind, &block, &mut oracle).unwrap();
let mut calls = 0;
let receipt =
visit(&mut Cursor::new(&block), 0, kind, bytes, |raw, derived| {
assert_eq!(raw, block);
assert_eq!(derived.len(), elements as usize * 4);
for (actual, reference) in
derived.as_chunks::<4>().0.iter().zip(&oracle)
{
let actual = f32::from_le_bytes(*actual);
if reference.is_nan() {
assert!(actual.is_nan());
} else {
assert_eq!(actual.to_bits(), reference.to_bits());
}
}
calls += 1;
Ok(())
})
.unwrap();
assert_eq!(calls, 1);
assert_eq!(receipt, elements * 4);
}
}
}
}
}
+29 -1
View File
@@ -1,6 +1,7 @@
# Leleka quantization foundation
`leleka-quant-core` provides IQ3_S, IQ4_NL, IQ4_XS, Q4_K, Q5_K and Q8_0 CPU decoding and binary16-to-binary32
`leleka-quant-core` provides IQ3_S, IQ4_NL, IQ4_XS, Q2_0, Q4_K, Q5_K, Q6_K and Q8_0
CPU decoding and binary16-to-binary32
conversion in an independent Rust crate. Production code uses only the standard
library: no build script, C/FFI, GGML, Strata source/process, Python or CUDA dependency.
`sha2` and `hex` are test-only dependencies for the existing golden checks.
@@ -88,6 +89,33 @@ See [Q4_K/Q5_K reference parity](../../docs/q4-q5-k-reference-parity.md) for the
separate pinned C-oracle scope and actual results. These CPU preparation ports
do not remove all control-plane C builds or qualify serving/model/GPU behavior.
Q2_0 accepts 18-byte blocks producing 64 values. Its little-endian FP16 scale
occupies bytes 0–1; each following byte contains four consecutive two-bit
elements, read from least to most significant bits. Codes 0, 1, 2 and 3 map to
quant values −1, 0, 1 and 2, then multiply `quant * scale`, following pinned
`dequantize_row_q2_0`. This format is GGUF kind 42, distinct from Q2_K.
Q6_K accepts 210-byte blocks producing 256 values. Its low quant bytes occupy
0–127, high quant bytes 128–191, signed int8 subscales 192–207 and little-endian
FP16 base scale 208–209. Two 128-value halves each contain four 32-value
quadrants. High-bit shifts 0/2/4/6 combine with the low/high nibbles, giving a
six-bit code minus 32; the subscale index uses a 16-element lane group within
each quadrant. Arithmetic follows pinned `dequantize_row_q6_K`, preserving
`(base * signed_subscale) * signed_quant` rather than reassociating products.
The −128 subscale remains signed. No codebook or K scale/minimum helper is used.
Both formats propagate all FP16 encodings, including NaN and infinity. Infinity
times zero quant, and Q6_K infinity times zero subscale, produce NaN; existing
consumer value policies stay unchanged. Shape errors fail before output writes,
empty bulk input/output is valid, and decoding requires neither a heap buffer
nor source alignment. Standalone synthetic tests check independent expected
wire values, every Q6_K packed lane/quadrant mapping, bulk/bounds behavior,
signed zero and nonfinite zero-factor cases. Separate pinned C oracles qualify
finite output bits and explicit nonfinite classification/sign behavior; they
do not imply portable NaN payloads, model/GPU support or performance results.
See [Q6_K/Q2_0 reference parity](../../docs/q6-k-q2-0-reference-parity.md) for
the recorded corpus, compiler and actual test results.
The existing tests preserve the SHA-256 of the little-endian grid bytes
(`bd1af4945a1717c65610b0284e4628b9a1ba3b306fae3a06f6e5f597356e349f`)
and the mixed-block decoded f32 bytes
+2
View File
@@ -6,8 +6,10 @@ mod iq3s_grid;
pub mod iq4_nl;
pub mod iq4_xs;
mod k_scale_min;
pub mod q2_0;
pub mod q4_k;
pub mod q5_k;
pub mod q6_k;
pub mod q8_0;
pub fn f16_bits_to_f32(bits: u16) -> f32 {
+131
View File
@@ -0,0 +1,131 @@
//! Allocation-free CPU decoding of GGML Q2_0 blocks (64 values / 18 bytes).
//! Layout/arithmetic follow llama.cpp 3cf03257f219afbe7334045ff7c6a06ac68c627d
//! `dequantize_row_q2_0` / `block_q2_0` (MIT, ggml authors; ../LICENSE-GGML).
//! Every FP16 encoding is admitted, preserving consumer nonfinite policies.
use crate::f16_bits_to_f32;
pub const BLOCK_BYTES: usize = 18;
pub const BLOCK_ELEMENTS: usize = 64;
pub fn decode_block(block: &[u8; BLOCK_BYTES]) -> Result<[f32; BLOCK_ELEMENTS], String> {
let scale = f16_bits_to_f32(u16::from_le_bytes([block[0], block[1]]));
let mut output = [0.0; BLOCK_ELEMENTS];
for (element, value) in output.iter_mut().enumerate() {
let code = (block[2 + element / 4] >> (2 * (element % 4))) & 3;
let quant = i32::from(code) - 1;
*value = quant as f32 * scale;
}
Ok(output)
}
/// Invalid shapes fail before output writes. Empty slices form a zero-block
/// operation; decoding needs no alignment or heap buffer.
pub fn decode_into(blocks: &[u8], output: &mut [f32]) -> Result<(), String> {
if !blocks.len().is_multiple_of(BLOCK_BYTES)
|| (blocks.len() / BLOCK_BYTES)
.checked_mul(BLOCK_ELEMENTS)
.is_none_or(|expected| expected != output.len())
{
return Err("Q2_0 block and output lengths do not match".into());
}
for (block, values) in blocks
.as_chunks::<BLOCK_BYTES>()
.0
.iter()
.zip(output.as_chunks_mut::<BLOCK_ELEMENTS>().0.iter_mut())
{
values.copy_from_slice(&decode_block(block)?);
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn independent_wire_values_are_sequential_two_bit_fields() {
let mut block = [0u8; BLOCK_BYTES];
block[..2].copy_from_slice(&[0x00, 0x38]); // 0.5
block[2..].fill(0xe4); // 00,01,10,11 -> -1,0,1,2.
block[3] = 0x1b; // Reverse order.
block[17] = 0xff; // Last byte, all +2.
let output = decode_block(&block).unwrap();
assert_eq!(&output[..8], &[-0.5, 0.0, 0.5, 1.0, 1.0, 0.5, 0.0, -0.5]);
for quartet in output[8..60].as_chunks::<4>().0 {
assert_eq!(quartet, &[-0.5, 0.0, 0.5, 1.0]);
}
assert_eq!(&output[60..], &[1.0; 4]);
}
#[test]
fn unaligned_bulk_and_invalid_shapes_preserve_contract() {
let mut block = [0u8; BLOCK_BYTES];
block[..2].copy_from_slice(&0x3c00u16.to_le_bytes());
block[2..].fill(0xe4);
let mut storage = [0u8; 2 * BLOCK_BYTES + 16];
let start = storage.as_ptr().align_offset(16) + 1;
let source = &mut storage[start..start + 2 * BLOCK_BYTES];
assert_eq!(source.as_ptr().align_offset(16), 15);
source[..BLOCK_BYTES].copy_from_slice(&block);
source[BLOCK_BYTES..].copy_from_slice(&block);
let mut output = [123.0; 2 * BLOCK_ELEMENTS];
decode_into(source, &mut output).unwrap();
for quartet in output.as_chunks::<4>().0 {
assert_eq!(quartet, &[-1.0, 0.0, 1.0, 2.0]);
}
for length in [0, 1, BLOCK_BYTES - 1, BLOCK_BYTES + 1, source.len() - 1] {
output.fill(123.0);
assert!(decode_into(&source[..length], &mut output).is_err());
assert_eq!(output, [123.0; 2 * BLOCK_ELEMENTS]);
}
for length in [
0,
BLOCK_ELEMENTS - 1,
BLOCK_ELEMENTS + 1,
2 * BLOCK_ELEMENTS,
] {
output.fill(123.0);
assert!(decode_into(&source[..BLOCK_BYTES], &mut output[..length]).is_err());
assert_eq!(output, [123.0; 2 * BLOCK_ELEMENTS]);
}
decode_into(&[], &mut []).unwrap();
}
#[test]
fn signed_zero_and_nonfinite_scales_are_admitted() {
let mut block = [0u8; BLOCK_BYTES];
block[2..].fill(0xe4);
for (scale, expected) in [
(0x0000u16, [0x8000_0000u32, 0, 0, 0]),
(0x8000, [0, 0x8000_0000, 0x8000_0000, 0x8000_0000]),
] {
block[..2].copy_from_slice(&scale.to_le_bytes());
for quartet in decode_block(&block).unwrap().as_chunks::<4>().0 {
for (value, bits) in quartet.iter().zip(expected) {
assert_eq!(value.to_bits(), bits);
}
}
}
for scale in [0x7c00u16, 0xfc00, 0x7c01, 0xfc01, 0x7e00, 0xfe00] {
block[..2].copy_from_slice(&scale.to_le_bytes());
let mut output = [0.0; BLOCK_ELEMENTS];
decode_into(&block, &mut output).unwrap();
for quartet in output.as_chunks::<4>().0 {
if scale & 0x03ff != 0 {
assert!(quartet.iter().all(|v| v.is_nan()));
} else {
assert!(quartet[1].is_nan()); // Infinity times quant zero.
for index in [0, 2, 3] {
assert!(quartet[index].is_infinite());
assert_eq!(
quartet[index].is_sign_negative(),
(scale & 0x8000 != 0) ^ (index == 0)
);
}
}
}
}
}
}
+223
View File
@@ -0,0 +1,223 @@
//! Allocation-free CPU decoding of GGML Q6_K blocks (256 values / 210 bytes).
//! Layout/arithmetic follow llama.cpp 3cf03257f219afbe7334045ff7c6a06ac68c627d
//! `dequantize_row_q6_K` / `block_q6_K` (MIT, ggml authors; ../LICENSE-GGML).
//! Every FP16 encoding is admitted, preserving consumer nonfinite policies.
use crate::f16_bits_to_f32;
pub const BLOCK_BYTES: usize = 210;
pub const BLOCK_ELEMENTS: usize = 256;
pub fn decode_block(block: &[u8; BLOCK_BYTES]) -> Result<[f32; BLOCK_ELEMENTS], String> {
let base = f16_bits_to_f32(u16::from_le_bytes([block[208], block[209]]));
let mut output = [0.0; BLOCK_ELEMENTS];
for half in 0..2 {
for lane in 0..32 {
let low1 = block[64 * half + lane];
let low2 = block[64 * half + lane + 32];
let high = block[128 + 32 * half + lane];
let quants = [
((low1 & 15) | ((high & 3) << 4)) as i8 - 32,
((low2 & 15) | (((high >> 2) & 3) << 4)) as i8 - 32,
((low1 >> 4) | (((high >> 4) & 3) << 4)) as i8 - 32,
((low2 >> 4) | (((high >> 6) & 3) << 4)) as i8 - 32,
];
for (quadrant, quant) in quants.into_iter().enumerate() {
let scale = block[192 + 8 * half + 2 * quadrant + lane / 16] as i8;
// Preserve the C intermediate multiplication before the quant
// multiply, including infinity times zero producing NaN.
let scaled = base * f32::from(scale);
output[128 * half + 32 * quadrant + lane] = scaled * f32::from(quant);
}
}
}
Ok(output)
}
/// Invalid shapes fail before output writes. Empty slices form a zero-block
/// operation; decoding needs no alignment or heap buffer.
pub fn decode_into(blocks: &[u8], output: &mut [f32]) -> Result<(), String> {
if !blocks.len().is_multiple_of(BLOCK_BYTES)
|| (blocks.len() / BLOCK_BYTES)
.checked_mul(BLOCK_ELEMENTS)
.is_none_or(|expected| expected != output.len())
{
return Err("Q6_K block and output lengths do not match".into());
}
for (block, values) in blocks
.as_chunks::<BLOCK_BYTES>()
.0
.iter()
.zip(output.as_chunks_mut::<BLOCK_ELEMENTS>().0.iter_mut())
{
values.copy_from_slice(&decode_block(block)?);
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
fn known_block(scale_bits: u16) -> [u8; BLOCK_BYTES] {
let mut block = [0u8; BLOCK_BYTES];
block[..64].fill(0xa1);
block[64..128].fill(0x4f);
block[128..160].fill(0xe4);
block[160..192].fill(0x1b);
let scales = [
-128i8, -3, -1, 0, 1, 2, 63, 127, -127, -64, -2, 1, 3, 4, 64, 126,
];
for (byte, scale) in block[192..208].iter_mut().zip(scales) {
*byte = scale as u8;
}
block[208..].copy_from_slice(&scale_bits.to_le_bytes());
block
}
#[test]
fn independent_expected_values_cover_signed_scales_halves_and_quadrants() {
let output = decode_block(&known_block(0x3800)).unwrap(); // d=0.5
// First-half quants [-31,-15,10,26]; second [31,15,-12,-28].
// Independently calculated values for each 16-element scale group.
let expected = [
1984.0f32, 46.5, 7.5, -0.0, 5.0, 10.0, 819.0, 1651.0, -1968.5, -992.0, -15.0, 7.5,
-18.0, -24.0, -896.0, -1764.0,
];
for (group, expected) in output.as_chunks::<16>().0.iter().zip(expected) {
assert!(
group
.iter()
.all(|value| value.to_bits() == expected.to_bits())
);
}
}
#[test]
fn single_packed_bits_map_to_exact_lanes_in_both_halves() {
let mut block = [0u8; BLOCK_BYTES];
block[192..208].fill(1);
block[208..].copy_from_slice(&0x3c00u16.to_le_bytes());
for position in 0..128 {
for (bit, quadrant_delta) in [(1u8, 0), (16, 2)] {
block[position] = bit;
let output = decode_block(&block).unwrap();
let half = position / 64;
let local = position % 64;
let quadrant = local / 32 + quadrant_delta;
let changed = 128 * half + 32 * quadrant + local % 32;
for (element, value) in output.into_iter().enumerate() {
assert_eq!(value, if element == changed { -31.0 } else { -32.0 });
}
block[position] = 0;
}
}
for position in 0..64 {
for quadrant in 0..4 {
block[128 + position] = 1 << (2 * quadrant);
let output = decode_block(&block).unwrap();
let changed = 128 * (position / 32) + 32 * quadrant + position % 32;
for (element, value) in output.into_iter().enumerate() {
assert_eq!(value, if element == changed { -16.0 } else { -32.0 });
}
block[128 + position] = 0;
}
}
}
#[test]
fn unaligned_bulk_and_invalid_shapes_preserve_contract() {
let block = known_block(0x3800);
let mut storage = vec![0u8; 2 * BLOCK_BYTES + 16];
let start = storage.as_ptr().align_offset(16) + 1;
let source = &mut storage[start..start + 2 * BLOCK_BYTES];
assert_eq!(source.as_ptr().align_offset(16), 15);
source[..BLOCK_BYTES].copy_from_slice(&block);
source[BLOCK_BYTES..].copy_from_slice(&block);
let mut output = [123.0; 2 * BLOCK_ELEMENTS];
decode_into(source, &mut output).unwrap();
let expected = decode_block(&block).unwrap();
for (value, expected) in output.iter().zip(expected.into_iter().cycle()) {
assert_eq!(value.to_bits(), expected.to_bits());
}
for length in [0, 1, BLOCK_BYTES - 1, BLOCK_BYTES + 1, source.len() - 1] {
output.fill(123.0);
assert!(decode_into(&source[..length], &mut output).is_err());
assert_eq!(output, [123.0; 2 * BLOCK_ELEMENTS]);
}
for length in [
0,
BLOCK_ELEMENTS - 1,
BLOCK_ELEMENTS + 1,
2 * BLOCK_ELEMENTS,
] {
output.fill(123.0);
assert!(decode_into(&source[..BLOCK_BYTES], &mut output[..length]).is_err());
assert_eq!(output, [123.0; 2 * BLOCK_ELEMENTS]);
}
decode_into(&[], &mut []).unwrap();
}
#[test]
fn signed_zero_preserves_signed_scale_and_quant_multiplications() {
let signs = [
false, false, false, true, false, false, false, false, true, true, true, false, true,
true, true, true,
];
for scale in [0x0000u16, 0x8000] {
let output = decode_block(&known_block(scale)).unwrap();
for (group, negative) in output.as_chunks::<16>().0.iter().zip(signs) {
let bits = if negative ^ (scale == 0x8000) {
0x8000_0000
} else {
0
};
assert!(group.iter().all(|value| value.to_bits() == bits));
}
}
}
#[test]
fn nonfinite_scales_zero_subscales_and_zero_quants_are_admitted() {
let signs = [
false, false, false, true, false, false, false, false, true, true, true, false, true,
true, true, true,
];
for scale in [0x7c00u16, 0xfc00, 0x7c01, 0xfc01, 0x7e00, 0xfe00] {
let block = known_block(scale);
let mut output = [0.0; BLOCK_ELEMENTS];
decode_into(&block, &mut output).unwrap();
for (index, (group, negative)) in
output.as_chunks::<16>().0.iter().zip(signs).enumerate()
{
if scale & 0x03ff != 0 || index == 3 {
assert!(group.iter().all(|value| value.is_nan()));
} else {
let sign = negative ^ (scale & 0x8000 != 0);
assert!(
group
.iter()
.all(|value| value.is_infinite() && value.is_sign_negative() == sign)
);
}
}
let mut zero_quant = block;
zero_quant[..128].fill(0);
zero_quant[128..192].fill(0xaa); // Every six-bit code is 32, hence quant zero.
assert!(
decode_block(&zero_quant)
.unwrap()
.iter()
.all(|value| value.is_nan())
);
let mut zero_subscale = block;
zero_subscale[192..208].fill(0);
assert!(
decode_block(&zero_subscale)
.unwrap()
.iter()
.all(|value| value.is_nan())
);
}
}
}
+111
View File
@@ -0,0 +1,111 @@
# Q6_K / Q2_0 CPU reference parity
GGUF kind 14 (Q6_K) and kind 42 (Q2_0) preparation decoding gains explicit
independent Rust routes. This does not replace the full inference engine.
Other unported preparation formats still use the C bridge; no GPU, model or
user-agent data is accessed by these synthetic CPU gates.
## Pinned reference and layout
Expected numeric output comes from the unchanged vendored GGML C implementation,
llama.cpp `3cf03257f219afbe7334045ff7c6a06ac68c627d` and imported Strata
`d9ab8435f654c368c586340d490915f6addf56a3`. Source hashes and original MIT notice
remain in [GGML provenance](../control-plane/third_party/ggml/UPSTREAM.md) and
[the crate notice](../crates/quant-core/LICENSE-GGML). The C bridge production
code, compiler arithmetic flags, nineteen previous oracle tests and eleven
previous visitor test functions remain unchanged.
Q6_K is 210 bytes / 256 outputs: low nibble bank 0–127, high two-bit bank
128–191, sixteen signed int8 subscales 192–207, little-endian FP16 header
208–209. Each 128-output half uses separate low/high/scale offsets; each has
four 32-output quadrants and two 16-lane subscale positions per quadrant.
Arithmetic keeps `(d * signed_subscale) * (six_bit_code - 32)` in C order.
Q2_0 is 18 bytes / 64 outputs: little-endian FP16 header 0–1 and sixteen
packed bytes 2–17. Four consecutive two-bit fields in each byte map to
`{-1, 0, 1, 2}` and multiply as `(code - 1) * d`, matching pinned C order.
Both formats admit every FP16 encoding as the old C consumers do. Inf times
zero subscale or zero signed quant yields NaN; all non-NaN values including
signed zero and infinity signs use exact bits. NaN payload/sign equivalence
is outside this classification contract. Bulk shape errors must not write
caller output.
## Independent synthetic coverage
The input generators and coverage bookkeeping never call Rust unpack helpers.
Every expected numeric value is actual C output, not a Rust-derived expectation.
- Every **63,488 finite FP16 encoding**: one Q6_K block and four Q2_0 blocks
per header. The four Q2 patterns put each code at every output position.
This contributes **32,505,856** finite comparisons.
- Every **256 signed subscale × 64 quant code** pair at each of Q6_K's 256
output positions with one fixed finite header; assertions cover both halves,
all quadrants/lanes and every subscale location. This contributes
**4,194,304** comparisons.
- Independent byte bijections exercise every one of 256 byte values at all
208 Q6 packed-field positions and all sixteen Q2 packed-byte positions.
Q2 coverage additionally requires every code at all 64 consecutive outputs.
These contribute **81,920** comparisons.
- Sixteen-block finite boundary batches through aligned and deliberately
unaligned bulk slices contribute **10,240** comparisons. Empty/truncated
source and short/long output shapes reject before modifying sentinel output,
in both Rust and C APIs.
- Every **2,048 nonfinite FP16 encoding** is tested for Q6 generated fields,
explicit zero subscales and explicit zero signed quants, and Q2's four
code-position patterns. NaN class agrees; every non-NaN output matches bits.
Total finite comparisons: **36,792,320**, with zero tolerance.
This exhausts separate domains, not the full FP16 × signed-subscale × quant
joint space, all arbitrary packed-field combinations or NaN payloads.
## Bounded visitor
Only kinds 14 and 42 gain routes; geometry agreement is checked before seek.
The source cap and other routes are unchanged. Synthetic tensors cross two
callbacks: exact C bytes, source offsets/slices, bounded derived buffers and
F32 byte receipts are checked. Malformed shapes do not seek or call back;
early/late truncation cannot deliver partial chunks; callback failure at the
first or second callback stops further reads. Nonfinite and signed-zero
headers with explicit zero factors retain C output semantics.
```sh
cargo test --locked -p leleka-quant-core
cargo clippy --locked -p leleka-quant-core --all-targets -- -D warnings
cargo test --locked -p strata-control --lib ggml_bridge::tests -- --test-threads=2
cargo test --locked -p strata-control --lib gguf_f32_stream::tests
```
## Actual results
Local CPU gates on 2026-10-07:
- Rust `1.99.0 (b940084d7 2026-09-28)`, Darwin arm64, Apple Clang 21.0.0
(`clang-2100.1.1.101`); unchanged C arithmetic flags and zero tolerance.
- Actual pinned C oracle: **24 passed, 0 failed**, including five new tests
and nineteen previous tests byte-preserved. All **36,792,320** new finite
comparisons and every field/per-position scale-code coverage assertion passed
with zero numerical mismatch. All nonfinite, zero-factor, bulk and sentinel
gates passed. The complete oracle runtime was 16.63 seconds, a test duration
rather than an inference performance result.
- Visitor: **13 passed, 0 failed**, including two new tests and eleven previous
functions byte-preserved. Q6 used raw chunks **28,140 / 3,570 bytes**, derived
chunks **137,216 / 17,408 bytes**. Q2 used raw **28,152 / 306 bytes**, derived
**400,384 / 4,352 bytes**. Offset, bounded-buffer, receipt, early/late truncation,
malformed-shape, first/second callback abort and nonfinite/zero-factor tests
passed.
- Control-plane library/tests Clippy with warnings denied, full workspace
formatting, diff checks, all ten vendored GGML source hash checks and
quant-core normal dependency tree passed. The tree contains only the
independent Rust crate, with no production dependencies.
- Standalone quant-core: **28 passed, 0 failed** (eight new: five Q6 and
three Q2 tests), all-target Clippy with warnings denied, formatting and
normal dependency tree passed. The initial 28/28 test run also passed;
a test-only temporary-vector lint was corrected to equivalent stack storage
before the final gate, with no arithmetic or assertion change. The final
owned temporary target was cleaned (359 files, 16.1 MiB) and removed; the
earlier Clippy target was also removed.
- Existing coordinated shared control-plane target cache retained; no new
private control-plane build target or test artifact was created.
Linux/compiler qualification, model/GPU inference, quality and paired end-to-end
performance are separate gates. No performance or inference-readiness claim is made.