From 4ed6914d8409276a38929c423b0149a08c467ab7 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Wed, 7 Oct 2026 21:27:55 +0200 Subject: [PATCH] STRA-102 port Q8_0 and IQ4_XS preparation to Rust --- control-plane/src/ggml_bridge.rs | 225 +++++++++++++++++++++++++++ control-plane/src/gguf_f32_stream.rs | 166 +++++++++++++++++++- crates/quant-core/README.md | 23 ++- crates/quant-core/src/iq4_nl.rs | 2 +- crates/quant-core/src/iq4_xs.rs | 188 ++++++++++++++++++++++ crates/quant-core/src/lib.rs | 2 + crates/quant-core/src/q8_0.rs | 124 +++++++++++++++ docs/q8-iq4xs-reference-parity.md | 106 +++++++++++++ 8 files changed, 829 insertions(+), 7 deletions(-) create mode 100644 crates/quant-core/src/iq4_xs.rs create mode 100644 crates/quant-core/src/q8_0.rs create mode 100644 docs/q8-iq4xs-reference-parity.md diff --git a/control-plane/src/ggml_bridge.rs b/control-plane/src/ggml_bridge.rs index 86a91766..4a486c78 100644 --- a/control-plane/src/ggml_bridge.rs +++ b/control-plane/src/ggml_bridge.rs @@ -355,4 +355,229 @@ mod tests { decode_into(42, &q2, &mut values).unwrap(); assert!(values.iter().all(|value| *value == -1.0)); } + + fn q8_corpus(scale: u16) -> [u8; 8 * 34] { + let mut source = [0u8; 8 * 34]; + for (group, block) in source.as_chunks_mut::<34>().0.iter_mut().enumerate() { + block[..2].copy_from_slice(&scale.to_le_bytes()); + for (position, byte) in block[2..].iter_mut().enumerate() { + *byte = (group as u8 * 32 + position as u8).wrapping_add(scale as u8); + } + } + source + } + + #[test] + fn pinned_ggml_q8_matches_rust_bits_for_every_finite_scale_and_signed_codepoint() { + use leleka_quant_core::q8_0; + let mut position_codes = [[false; 256]; 32]; + let mut compared = 0; + for scale in 0..=u16::MAX { + if scale & 0x7c00 == 0x7c00 { + continue; + } + let source = q8_corpus(scale); + let mut reference = [0.0; 256]; + let mut actual = [0.0; 256]; + decode_into(8, &source, &mut reference).unwrap(); + q8_0::decode_into(&source, &mut actual).unwrap(); + let mut scale_codes = [false; 256]; + for block in source.as_chunks::<34>().0 { + for (position, code) in block[2..].iter().enumerate() { + position_codes[position][usize::from(*code)] = true; + scale_codes[usize::from(*code)] = true; + } + } + assert!(scale_codes.into_iter().all(|seen| seen)); + for (element, (actual, reference)) in actual.iter().zip(&reference).enumerate() { + assert!(actual.is_finite() && reference.is_finite()); + assert_eq!( + actual.to_bits(), + reference.to_bits(), + "Q8_0 scale={scale:#06x} element={element}" + ); + } + compared += 1; + } + assert_eq!(compared, 63_488); + assert!(position_codes.iter().flatten().all(|seen| *seen)); + } + + #[test] + fn pinned_ggml_q8_nonfinite_including_zero_matches_rust_classification_and_inf_signs() { + use leleka_quant_core::q8_0; + let mut compared = 0; + for scale in 0..=u16::MAX { + if scale & 0x7c00 != 0x7c00 { + continue; + } + let source = q8_corpus(scale); + let mut reference = [0.0; 256]; + let mut actual = [0.0; 256]; + decode_into(8, &source, &mut reference).unwrap(); + q8_0::decode_into(&source, &mut actual).unwrap(); + let mut nan_count = 0; + for (actual, reference) in actual.iter().zip(&reference) { + if reference.is_nan() { + assert!(actual.is_nan()); + nan_count += 1; + } else { + assert!(actual.is_infinite() && reference.is_infinite()); + assert_eq!(actual.to_bits(), reference.to_bits()); + } + } + assert_eq!(nan_count, if scale & 0x03ff == 0 { 1 } else { 256 }); + compared += 1; + } + assert_eq!(compared, 2_048); + } + + fn iq4xs_corpus(scale: u16, group: usize) -> [u8; 136] { + let mut block = [0u8; 136]; + block[..2].copy_from_slice(&scale.to_le_bytes()); + let mut high = 0u16; + for subblock in 0..8 { + let six = (group * 8 + subblock + usize::from(scale)) & 63; + block[4 + subblock / 2] |= ((six & 15) as u8) << (4 * (subblock % 2)); + high |= ((six >> 4) as u16) << (2 * subblock); + for position in 0..16 { + let low = (position + usize::from(scale) + group) & 15; + let upper = (15 - position + (usize::from(scale) >> 4) + group) & 15; + block[8 + subblock * 16 + position] = low as u8 | ((upper as u8) << 4); + } + } + block[2..4].copy_from_slice(&high.to_le_bytes()); + block + } + + #[test] + fn pinned_ggml_iq4xs_matches_rust_bits_for_every_finite_scale_subscale_and_codepoint() { + use leleka_quant_core::iq4_xs; + let mut subscales = [[false; 64]; 8]; + let mut packed_fields = [[false; 256]; 128]; + let mut codepoints = [[false; 16]; 256]; + let mut compared = 0; + for scale in 0..=u16::MAX { + if scale & 0x7c00 == 0x7c00 { + continue; + } + let mut scale_subscales = [false; 64]; + for group in 0..8 { + let block = iq4xs_corpus(scale, group); + let high = u16::from_le_bytes([block[2], block[3]]); + for subblock in 0..8 { + let six = usize::from((block[4 + subblock / 2] >> (4 * (subblock % 2))) & 15) + | (usize::from((high >> (2 * subblock)) & 3) << 4); + subscales[subblock][six] = true; + scale_subscales[six] = true; + let mut low_seen = [false; 16]; + let mut high_seen = [false; 16]; + for position in 0..16 { + let field = subblock * 16 + position; + let packed = block[8 + field]; + packed_fields[field][usize::from(packed)] = true; + codepoints[subblock * 32 + position][usize::from(packed & 15)] = true; + codepoints[subblock * 32 + position + 16][usize::from(packed >> 4)] = true; + low_seen[usize::from(packed & 15)] = true; + high_seen[usize::from(packed >> 4)] = true; + } + assert!(low_seen.into_iter().all(|seen| seen)); + assert!(high_seen.into_iter().all(|seen| seen)); + } + let mut reference = [0.0; iq4_xs::BLOCK_ELEMENTS]; + decode_into(23, &block, &mut reference).unwrap(); + let actual = iq4_xs::decode_block(&block).unwrap(); + for (element, (actual, reference)) in actual.iter().zip(&reference).enumerate() { + assert!(actual.is_finite() && reference.is_finite()); + assert_eq!( + actual.to_bits(), + reference.to_bits(), + "IQ4_XS scale={scale:#06x} group={group} element={element}" + ); + } + } + assert!(scale_subscales.into_iter().all(|seen| seen)); + compared += 1; + } + assert_eq!(compared, 63_488); + assert!(subscales.iter().flatten().all(|seen| *seen)); + assert!(packed_fields.iter().flatten().all(|seen| *seen)); + assert!(codepoints.iter().flatten().all(|seen| *seen)); + } + + #[test] + fn pinned_ggml_iq4xs_nonfinite_and_zero_subscale_match_rust_classification_and_inf_signs() { + use leleka_quant_core::iq4_xs; + let mut zero_positions = [false; 8]; + let mut compared = 0; + for scale in 0..=u16::MAX { + if scale & 0x7c00 != 0x7c00 { + continue; + } + let mut nan_count = 0; + for group in 0..8 { + let block = iq4xs_corpus(scale, group); + let mut reference = [0.0; iq4_xs::BLOCK_ELEMENTS]; + let mut actual = [0.0; iq4_xs::BLOCK_ELEMENTS]; + decode_into(23, &block, &mut reference).unwrap(); + iq4_xs::decode_into(&block, &mut actual).unwrap(); + let high = u16::from_le_bytes([block[2], block[3]]); + for subblock in 0..8 { + let six = ((block[4 + subblock / 2] >> (4 * (subblock % 2))) & 15) + | (((high >> (2 * subblock)) & 3) as u8) << 4; + zero_positions[subblock] |= six == 32; + } + for (actual, reference) in actual.iter().zip(&reference) { + if reference.is_nan() { + assert!(actual.is_nan()); + nan_count += 1; + } else { + assert!(actual.is_infinite() && reference.is_infinite()); + assert_eq!(actual.to_bits(), reference.to_bits()); + } + } + } + assert_eq!(nan_count, if scale & 0x03ff == 0 { 32 } else { 2048 }); + compared += 1; + } + assert_eq!(compared, 2_048); + assert!(zero_positions.into_iter().all(|seen| seen)); + } + + #[test] + fn pinned_ggml_q8_and_iq4xs_unaligned_batches_match_rust_bits() { + use leleka_quant_core::{iq4_xs, q8_0}; + for (kind, block_bytes, elements) in [ + (8, q8_0::BLOCK_BYTES, q8_0::BLOCK_ELEMENTS), + (23, iq4_xs::BLOCK_BYTES, iq4_xs::BLOCK_ELEMENTS), + ] { + let scales = [ + 0x0000, 0x8000, 0x0001, 0x8001, 0x03ff, 0x83ff, 0x0400, 0x8400, 0x3555, 0xb555, + 0x3c00, 0xbc00, 0x7bff, 0xfbff, + ]; + let mut storage = vec![0u8; scales.len() * block_bytes + 16]; + let start = storage.as_ptr().align_offset(16) + 1; + let source = &mut storage[start..start + scales.len() * block_bytes]; + assert_eq!(source.as_ptr().align_offset(16), 15); + for (number, scale) in scales.into_iter().enumerate() { + let destination = &mut source[number * block_bytes..(number + 1) * block_bytes]; + if kind == 8 { + destination.copy_from_slice(&q8_corpus(scale)[..34]); + } else { + destination.copy_from_slice(&iq4xs_corpus(scale, number % 8)); + } + } + let mut reference = vec![0.0; scales.len() * elements]; + let mut actual = vec![0.0; reference.len()]; + decode_into(kind, source, &mut reference).unwrap(); + if kind == 8 { + q8_0::decode_into(source, &mut actual).unwrap(); + } else { + iq4_xs::decode_into(source, &mut actual).unwrap(); + } + for (actual, reference) in actual.iter().zip(&reference) { + assert_eq!(actual.to_bits(), reference.to_bits()); + } + } + } } diff --git a/control-plane/src/gguf_f32_stream.rs b/control-plane/src/gguf_f32_stream.rs index 07cf7312..016fe18c 100644 --- a/control-plane/src/gguf_f32_stream.rs +++ b/control-plane/src/gguf_f32_stream.rs @@ -3,7 +3,7 @@ use std::io::{Read, Seek, SeekFrom}; -use leleka_quant_core::iq4_nl; +use leleka_quant_core::{iq4_nl, iq4_xs, q8_0}; use crate::{ggml_bridge, gguf, iq3_s, kar_codec}; @@ -25,11 +25,18 @@ where { let (block_elements, block_bytes) = gguf::block_geometry(source_kind) .ok_or_else(|| format!("unsupported GGUF source kind {source_kind}"))?; - if source_kind == 20 - && (block_elements != iq4_nl::BLOCK_ELEMENTS as u64 - || block_bytes != iq4_nl::BLOCK_BYTES as u64) + let rust_geometry = match source_kind { + 8 => Some((q8_0::BLOCK_ELEMENTS, q8_0::BLOCK_BYTES, "Q8_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, + }; + if let Some((elements, bytes, format)) = rust_geometry + && (block_elements != elements as u64 || block_bytes != bytes as u64) { - return Err("IQ4_NL decoder geometry differs from GGUF source kind 20".into()); + return Err(format!( + "{format} decoder geometry differs from GGUF source kind {source_kind}" + )); } let block_bytes = usize::try_from(block_bytes).map_err(|_| "GGUF block is too large")?; if block_bytes > SOURCE_CHUNK_BYTES { @@ -68,6 +75,14 @@ where } callback(source, &derived)?; } + 8 => { + for block in source.as_chunks::<{ q8_0::BLOCK_BYTES }>().0 { + for value in q8_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)? { @@ -84,6 +99,14 @@ where } callback(source, &derived)?; } + 23 => { + for block in source.as_chunks::<{ iq4_xs::BLOCK_BYTES }>().0 { + for value in iq4_xs::decode_block(block)? { + derived.extend_from_slice(&value.to_le_bytes()); + } + } + callback(source, &derived)?; + } _ => { let values = (count / block_bytes) .checked_mul(block_elements as usize) @@ -322,6 +345,139 @@ mod tests { } } + #[test] + fn q8_and_iq4xs_streams_preserve_bounded_c_bytes_offsets_and_receipts() { + for kind in [8, 23] { + 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]; + let scale: u16 = [0, 0x8000, 1, 0x83ff, 0x0400, 0x3800, 0xbc00, 0x7bff][number % 8]; + block[..2].copy_from_slice(&scale.to_le_bytes()); + for (position, byte) in block[2..].iter_mut().enumerate() { + *byte = (number * 17 + position * 29) as u8; + } + source.extend_from_slice(&block); + } + let source_bytes = 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, + source_bytes 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 = 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, source_bytes); + assert_eq!(receipt, blocks as u64 * elements * 4); + assert_eq!(cursor.position(), (prefix + source_bytes) as u64); + let mut calls = 0; + assert!( + visit( + &mut Cursor::new(&source), + prefix as u64, + kind, + source_bytes as u64 - 1, + |_, _| { + calls += 1; + Ok(()) + } + ) + .is_err() + ); + assert_eq!(calls, 0); + let mut truncated = Cursor::new(&source[..prefix + bytes - 1]); + assert!( + visit(&mut truncated, prefix as u64, kind, bytes as u64, |_, _| { + calls += 1; + Ok(()) + }) + .is_err() + ); + assert_eq!(calls, 0); + let mut cursor = Cursor::new(&source); + let error = visit( + &mut cursor, + prefix as u64, + kind, + source_bytes as u64, + |_, _| { + calls += 1; + Err("owned callback abort".into()) + }, + ) + .unwrap_err(); + assert_eq!(error, "owned callback abort"); + assert_eq!(calls, 1); + assert_eq!(cursor.position(), (prefix + per_chunk * bytes) as u64); + } + } + + #[test] + fn q8_and_iq4xs_streams_preserve_nonfinite_classification_and_infinity_bits() { + for kind in [8, 23] { + let (elements, bytes) = gguf::block_geometry(kind).unwrap(); + for scale in [0x7c00u16, 0xfc00, 0x7c01, 0xfc01, 0x7e00, 0xfe00] { + let mut block = vec![0u8; bytes as usize]; + block[..2].copy_from_slice(&scale.to_le_bytes()); + for (position, byte) in block[2..].iter_mut().enumerate() { + *byte = (position * 29) as u8; + } + 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); + 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); + } + } + } + #[test] fn actual_target_quant_types_decode_one_block_each() { for kind in [8, 12, 13, 14, 18, 20, 21, 22, 23, 42] { diff --git a/crates/quant-core/README.md b/crates/quant-core/README.md index 8f57a72b..3f158be4 100644 --- a/crates/quant-core/README.md +++ b/crates/quant-core/README.md @@ -1,6 +1,6 @@ # Leleka quantization foundation -`leleka-quant-core` provides IQ3_S and IQ4_NL CPU decoding and binary16-to-binary32 +`leleka-quant-core` provides IQ3_S, IQ4_NL, IQ4_XS 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. @@ -43,6 +43,27 @@ bits; infinity output signs and bits are checked. See actual CPU results. This port removes IQ4_NL's computational C dependency in the preparation visitor; other legacy control-plane C paths and builds remain. +IQ4_XS accepts 136-byte blocks with 256 output elements. It shares IQ4_NL's +codebook through a crate-private constant; the public IQ4_NL API and table bytes +are unchanged. Each block stores a little-endian FP16 scale, little-endian 16-bit +packed scale highs, four packed scale-low bytes and 128 packed codepoint bytes. +Each of eight 32-element subblocks reconstructs a six-bit scale, subtracts 32, +then performs `base * multiplier` followed by `subblock_scale * codepoint`. +Low and high codepoint nibbles produce separate 16-element halves. This follows +the pinned `dequantize_row_iq4_xs` function and preserves its intermediate, +including signed zero and infinity times zero producing NaN. + +Q8_0 accepts 34-byte blocks with 32 output elements: a little-endian FP16 scale +and 32 signed bytes, decoded by scale multiplication as in the pinned +`dequantize_row_q8_0` function. IQ4_XS and Q8_0 admit every FP16 scale encoding; +existing consumers retain their nonfinite-value policy. Their bulk APIs reject +malformed shapes before writes, accept empty input/output, require no source +alignment, and use no heap decoding buffer. The separate pinned C-oracle gates +record exact finite bits and explicit nonfinite classification/infinity signs +without implying portable NaN payload/sign bits, GPU behavior or complete model +support. See [combined reference parity](../../docs/q8-iq4xs-reference-parity.md) +for actual corpus, compiler and results. + The existing tests preserve the SHA-256 of the little-endian grid bytes (`bd1af4945a1717c65610b0284e4628b9a1ba3b306fae3a06f6e5f597356e349f`) and the mixed-block decoded f32 bytes diff --git a/crates/quant-core/src/iq4_nl.rs b/crates/quant-core/src/iq4_nl.rs index a8fd910e..28cbc4b0 100644 --- a/crates/quant-core/src/iq4_nl.rs +++ b/crates/quant-core/src/iq4_nl.rs @@ -9,7 +9,7 @@ use crate::f16_bits_to_f32; pub const BLOCK_BYTES: usize = 18; pub const BLOCK_ELEMENTS: usize = 32; -const VALUES: [i8; 16] = [ +pub(crate) const VALUES: [i8; 16] = [ -127, -104, -83, -65, -49, -35, -22, -10, 1, 13, 25, 38, 53, 69, 89, 113, ]; diff --git a/crates/quant-core/src/iq4_xs.rs b/crates/quant-core/src/iq4_xs.rs new file mode 100644 index 00000000..afbc0c76 --- /dev/null +++ b/crates/quant-core/src/iq4_xs.rs @@ -0,0 +1,188 @@ +//! Bounded CPU decoding of GGML IQ4_XS blocks (256 values / 136 bytes). +//! Layout and arithmetic follow llama.cpp +//! 3cf03257f219afbe7334045ff7c6a06ac68c627d, `dequantize_row_iq4_xs`. +//! Uses the pinned IQ4_NL codebook (MIT, ggml authors; see ../LICENSE-GGML). +//! All FP16 scale encodings are admitted, including infinity and NaN. + +use crate::{f16_bits_to_f32, iq4_nl::VALUES}; + +pub const BLOCK_BYTES: usize = 136; +pub const BLOCK_ELEMENTS: usize = 256; + +/// Decode one complete block. Consumer nonfinite-value policy is unchanged: +/// infinity times a zero subblock multiplier produces NaN, as in pinned C. +pub fn decode_block(block: &[u8; BLOCK_BYTES]) -> Result<[f32; BLOCK_ELEMENTS], String> { + let base = f16_bits_to_f32(u16::from_le_bytes([block[0], block[1]])); + let high = u16::from_le_bytes([block[2], block[3]]); + let mut output = [0.0; BLOCK_ELEMENTS]; + for subblock in 0..8 { + let low = (block[4 + subblock / 2] >> (4 * (subblock % 2))) & 15; + let upper = ((high >> (2 * subblock)) & 3) as u8; + let multiplier = i32::from(low | (upper << 4)) - 32; + // Retain the C intermediate and multiplication order, including zero + // signs and infinity * zero. Do not combine these two multiplications. + let scale = base * multiplier as f32; + for index in 0..16 { + let packed = block[8 + 16 * subblock + index]; + output[32 * subblock + index] = scale * f32::from(VALUES[usize::from(packed & 15)]); + output[32 * subblock + index + 16] = + scale * f32::from(VALUES[usize::from(packed >> 4)]); + } + } + Ok(output) +} + +/// Decode into caller-owned storage without heap buffers or alignment needs. +/// Invalid shapes are rejected before any write; empty slices are a valid +/// zero-block operation. Each source block must have exactly 256 output values. +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("IQ4_XS block and output lengths do not match".into()); + } + for (block, values) in blocks + .as_chunks::() + .0 + .iter() + .zip(output.as_chunks_mut::().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[..2].copy_from_slice(&scale_bits.to_le_bytes()); + // Explicit wire bytes: six-bit scales [0,15,16,31,32,33,48,63], hence + // multipliers [-32,-17,-16,-1,0,1,16,31]. High bits are LE 0xfa50. + block[2..8].copy_from_slice(&[0x50, 0xfa, 0xf0, 0xf0, 0x10, 0xf0]); + for subblock in 0..8 { + for index in 0..16 { + block[8 + 16 * subblock + index] = index as u8 | ((15 - index as u8) << 4); + } + } + block + } + + #[test] + fn known_scale_bytes_and_split_half_values_match() { + let block = known_block(0x3800); // 0.5 + let actual = decode_block(&block).unwrap(); + // Expected scales and codebook values independently spelled out, not + // unpacked with the decoder's shifts or shared table. + let scales = [-16.0f32, -8.5, -8.0, -0.5, 0.0, 0.5, 8.0, 15.5]; + let codepoints = [ + -127.0f32, -104.0, -83.0, -65.0, -49.0, -35.0, -22.0, -10.0, 1.0, 13.0, 25.0, 38.0, + 53.0, 69.0, 89.0, 113.0, + ]; + for (subblock, scale) in scales.into_iter().enumerate() { + for (index, codepoint) in codepoints.into_iter().enumerate() { + assert_eq!( + actual[32 * subblock + index].to_bits(), + (scale * codepoint).to_bits() + ); + assert_eq!( + actual[32 * subblock + 31 - index].to_bits(), + (scale * codepoint).to_bits() + ); + } + } + assert_eq!(actual[0], 2032.0); + assert_eq!(actual[32], 1079.5); + assert_eq!(actual[224], -1968.5); + assert_eq!(actual[240], 1751.5); + } + + #[test] + fn bulk_handles_unaligned_blocks_and_rejects_shapes_before_writes() { + let blocks = [known_block(0x3800), known_block(0xbc00)]; + let mut storage = vec![0u8; BLOCK_BYTES * 2 + 16]; + let start = storage.as_ptr().align_offset(16) + 1; + let source = &mut storage[start..start + BLOCK_BYTES * 2]; + assert_eq!(source.as_ptr().align_offset(16), 15); + source[..BLOCK_BYTES].copy_from_slice(&blocks[0]); + source[BLOCK_BYTES..].copy_from_slice(&blocks[1]); + let mut output = [123.0; BLOCK_ELEMENTS * 2]; + decode_into(source, &mut output).unwrap(); + for (number, block) in blocks.iter().enumerate() { + let single = decode_block(block).unwrap(); + for (index, value) in single.into_iter().enumerate() { + assert_eq!( + output[number * BLOCK_ELEMENTS + index].to_bits(), + value.to_bits() + ); + } + } + for source_len in [0, 1, BLOCK_BYTES - 1, BLOCK_BYTES + 1, source.len() - 1] { + output.fill(123.0); + assert!(decode_into(&source[..source_len], &mut output).is_err()); + assert_eq!(output, [123.0; BLOCK_ELEMENTS * 2]); + } + for output_len in [ + 0, + BLOCK_ELEMENTS - 1, + BLOCK_ELEMENTS + 1, + BLOCK_ELEMENTS * 2, + ] { + output.fill(123.0); + assert!(decode_into(&source[..BLOCK_BYTES], &mut output[..output_len]).is_err()); + assert_eq!(output, [123.0; BLOCK_ELEMENTS * 2]); + } + decode_into(&[], &mut []).unwrap(); + } + + #[test] + fn signed_zero_keeps_both_multiplication_signs() { + for scale_bits in [0x0000u16, 0x8000] { + let actual = decode_block(&known_block(scale_bits)).unwrap(); + for (subblock, multiplier_negative) in + [true, true, true, true, false, false, false, false] + .into_iter() + .enumerate() + { + let negative_scale = (scale_bits == 0x8000) ^ multiplier_negative; + assert_eq!( + actual[32 * subblock].to_bits(), + if negative_scale { 0 } else { 0x8000_0000 } + ); + assert_eq!( + actual[32 * subblock + 16].to_bits(), + if negative_scale { 0x8000_0000 } else { 0 } + ); + } + } + } + + #[test] + fn nonfinite_scales_propagate_including_infinity_times_zero() { + for scale_bits in [0x7c00u16, 0xfc00, 0x7c01, 0xfc01, 0x7e00, 0xfe00] { + let block = known_block(scale_bits); + let mut output = [0.0; BLOCK_ELEMENTS]; + decode_into(&block, &mut output).unwrap(); + let single = decode_block(&block).unwrap(); + for subblock in 0..8 { + for element in 0..32 { + let index = 32 * subblock + element; + if scale_bits & 0x03ff != 0 || subblock == 4 { + assert!(output[index].is_nan() && single[index].is_nan()); + } else { + assert!(output[index].is_infinite() && single[index].is_infinite()); + let negative = (scale_bits & 0x8000 != 0) + ^ (subblock < 4) + ^ !(8..24).contains(&element); + assert_eq!(output[index].is_sign_negative(), negative); + assert_eq!(single[index].is_sign_negative(), negative); + } + } + } + } + } +} diff --git a/crates/quant-core/src/lib.rs b/crates/quant-core/src/lib.rs index 0ffd0017..0004f293 100644 --- a/crates/quant-core/src/lib.rs +++ b/crates/quant-core/src/lib.rs @@ -4,6 +4,8 @@ pub mod iq3_s; mod iq3s_grid; pub mod iq4_nl; +pub mod iq4_xs; +pub mod q8_0; pub fn f16_bits_to_f32(bits: u16) -> f32 { let sign = (u32::from(bits & 0x8000)) << 16; diff --git a/crates/quant-core/src/q8_0.rs b/crates/quant-core/src/q8_0.rs new file mode 100644 index 00000000..ba9f3fdd --- /dev/null +++ b/crates/quant-core/src/q8_0.rs @@ -0,0 +1,124 @@ +//! Bounded CPU decoding of GGML Q8_0 blocks (32 values / 34 bytes). +//! Layout/arithmetic follow llama.cpp 3cf03257f219afbe7334045ff7c6a06ac68c627d +//! `ggml-common.h::block_q8_0` and `ggml-quants.c::dequantize_row_q8_0`. +//! Original GGML code is MIT licensed; see ../LICENSE-GGML. +//! Nonfinite scales propagate, preserving the existing preparation C path. + +use crate::f16_bits_to_f32; + +pub const BLOCK_BYTES: usize = 34; +pub const BLOCK_ELEMENTS: usize = 32; + +/// Decode one block, retaining signed int8 conversion and C multiplication order. +/// All binary16 scale encodings are admitted, including NaN and infinity. +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 (value, quant) in output.iter_mut().zip(&block[2..]) { + *value = f32::from(*quant as i8) * scale; + } + Ok(output) +} + +/// Shape errors leave all output untouched. Empty input/output is a valid +/// zero-block operation; arbitrary input alignment is supported without allocation. +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("Q8_0 block and output lengths do not match".into()); + } + for (block, values) in blocks + .as_chunks::() + .0 + .iter() + .zip(output.as_chunks_mut::().0.iter_mut()) + { + values.copy_from_slice(&decode_block(block)?); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn signed_int8_boundaries_and_lane_order_match_known_values() { + let mut block = [0u8; BLOCK_BYTES]; + block[..2].copy_from_slice(&0x3800u16.to_le_bytes()); + block[2..8].copy_from_slice(&[0, 1, 127, 128, 255, 129]); + block[33] = 42; + let output = decode_block(&block).unwrap(); + assert_eq!(&output[..6], &[0.0, 0.5, 63.5, -64.0, -0.5, -63.5]); + assert!(output[6..31].iter().all(|value| value.to_bits() == 0)); + assert_eq!(output[31], 21.0); + let mut batch = [0.0; BLOCK_ELEMENTS * 2]; + decode_into(&block.repeat(2), &mut batch).unwrap(); + assert_eq!(&batch[..BLOCK_ELEMENTS], &output); + assert_eq!(&batch[BLOCK_ELEMENTS..], &output); + } + + #[test] + fn malformed_shapes_reject_without_modifying_output() { + let source = [0u8; BLOCK_BYTES * 2]; + for source_len in [1, 33, 35, 67] { + let mut output = [123.0; BLOCK_ELEMENTS * 2]; + assert!(decode_into(&source[..source_len], &mut output).is_err()); + assert_eq!(output, [123.0; BLOCK_ELEMENTS * 2]); + } + for output_len in [0, 31, 33, 64] { + let mut output = [123.0; BLOCK_ELEMENTS * 2]; + assert!(decode_into(&source[..BLOCK_BYTES], &mut output[..output_len]).is_err()); + assert_eq!(output, [123.0; BLOCK_ELEMENTS * 2]); + } + let mut output = [123.0; BLOCK_ELEMENTS]; + assert!(decode_into(&[], &mut output).is_err()); + assert_eq!(output, [123.0; BLOCK_ELEMENTS]); + decode_into(&[], &mut []).unwrap(); + } + + #[test] + fn signed_zero_and_infinity_times_zero_preserve_value_policy() { + let mut block = [0u8; BLOCK_BYTES]; + block[3] = 255; + block[4] = 1; + for (scale, zero, negative, positive) in [ + (0x0000u16, 0, 0x8000_0000, 0), + (0x8000, 0x8000_0000, 0, 0x8000_0000), + ] { + block[..2].copy_from_slice(&scale.to_le_bytes()); + let output = decode_block(&block).unwrap(); + assert_eq!(output[0].to_bits(), zero); + assert_eq!(output[1].to_bits(), negative); + assert_eq!(output[2].to_bits(), positive); + } + for scale in [0x7c00u16, 0xfc00, 0x7c01, 0xfc01] { + block[..2].copy_from_slice(&scale.to_le_bytes()); + let output = decode_block(&block).unwrap(); + assert!(output[0].is_nan()); + if scale & 0x03ff == 0 { + assert_eq!( + output[1].to_bits(), + if scale == 0x7c00 { + 0xff80_0000 + } else { + 0x7f80_0000 + } + ); + assert_eq!( + output[2].to_bits(), + if scale == 0x7c00 { + 0x7f80_0000 + } else { + 0xff80_0000 + } + ); + } else { + assert!(output.iter().all(|value| value.is_nan())); + } + } + } +} diff --git a/docs/q8-iq4xs-reference-parity.md b/docs/q8-iq4xs-reference-parity.md new file mode 100644 index 00000000..41d0d5c2 --- /dev/null +++ b/docs/q8-iq4xs-reference-parity.md @@ -0,0 +1,106 @@ +# Q8_0 and IQ4_XS CPU reference parity + +This source port replaces GGUF kind 8 (Q8_0) and kind 23 (IQ4_XS) preparation +arithmetic with independent Rust modules in `leleka-quant-core`. The crate has +no production dependency beyond the standard library and no C/FFI, Strata, +Python or CUDA build/runtime dependency. Remaining preparation formats still +use the control plane's existing GGML C decoder; complete inference remains +separate. + +## Pinned layouts and arithmetic + +The numerical oracle is the unchanged vendored `ggml-quants.c` from llama.cpp +`3cf03257f219afbe7334045ff7c6a06ac68c627d`, also pinned by imported Strata +`d9ab8435f654c368c586340d490915f6addf56a3`. Source hashes and MIT attribution +remain in [GGML provenance](../control-plane/third_party/ggml/UPSTREAM.md) +and [the crate's retained notice](../crates/quant-core/LICENSE-GGML). +No native source or compiler arithmetic flag is changed. + +- Q8_0: 34 bytes / 32 values. The little-endian FP16 scale occupies bytes 0–1; + remaining bytes are signed int8 values, including -128. Each output preserves + the pinned C operand order: `signed_quant * scale`. +- IQ4_XS: 136 bytes / 256 values. FP16 scale occupies bytes 0–1, little-endian + packed high scale bits bytes 2–3, low scale nibbles bytes 4–7 and value nibbles + bytes 8–135. Eight subblocks each produce 32 outputs. The six-bit subscale is + biased by -32; the intermediate is `scale * signed_subscale`, followed by + multiplication with the shared nonlinear IQ4 codebook. Low/high value nibbles + retain the two 16-element output halves. The codebook shared with IQ4_NL is + unchanged; moving it does not change its values or pin. + +Both APIs accept every FP16 scale encoding, matching their previous C paths. +Infinity times a zero Q8 quant or zero IQ4_XS subscale produces NaN. Consumers +retain responsibility for value admission. IQ3_S's existing nonfinite rejection +is unchanged. Shape errors reject before output writes, empty input/output is a +valid zero-block operation, and arbitrary input alignment requires no heap +allocation in the Rust decoders. + +## Independent oracle scope + +All fixtures are generated synthetic bytes; no model weights or user data are +read. Finite comparisons use actual pinned C decoder output and exact +`f32::to_bits()` equality, including signed zero, with zero numerical tolerance. + +- Q8_0 exhausts all **63,488 finite FP16 encodings** and all **256 signed byte + codes at every scale**: **16,252,928** element comparisons. Coverage assertions + additionally require every byte code at every one of the 32 output positions. +- IQ4_XS exhausts all **63,488 finite FP16 encodings**, all **64 signed subscales + at each scale** and all **16 nonlinear codes at each subscale**. Eight blocks + per scale produce **130,023,424** element comparisons, including both output + halves. Coverage assertions require every subscale at every one of eight + subblock positions, all 256 packed byte values at each of 128 fields, and all + 16 codepoints at each of 256 output positions. +- Every one of **2,048 nonfinite FP16 encodings** is admitted by both Rust bulk + APIs and C. NaN classification is compared; non-NaN infinities must match exact + bits/signs. Q8 infinity checks contain all signed codes including zero; + IQ4_XS checks contain every subscale including zero. No portable NaN payload + or sign equivalence is inferred. +- A separate 14-block finite boundary batch for each format compares both bulk + APIs using input intentionally one byte beyond a 16-byte boundary, exercising + the C bridge's alignment-copy behavior and Rust's alignment-free decoder. +- Standalone tests check independent expected values, signed zeros, lane layout, + multiple blocks, nonfinite admission and malformed shapes preserving output. + Root's separate bounded visitor tests cover integration, offsets, callback + aborts, truncation and F32 byte receipts. + +These corpora cover the stated scalar scale/codepoint domains and field +positions. They do not exhaust the joint space of all packed bytes or all +combinations of different subblock scales in one block, qualify an entire model, +prove Linux/GCC parity, measure performance or exercise a GPU. + +## Commands + +```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 local CPU result, 2026-10-07 + +- Rust: `rustc 1.99.0 (b940084d7 2026-09-28)`. +- Host: `aarch64-apple-darwin` (Darwin arm64). +- C compiler: Apple Clang 21.0.0 (`clang-2100.1.1.101`). +- Standalone quant crate: **12 passed, 0 failed** (three new Q8_0 and four new + IQ4_XS tests); all-target Clippy with warnings denied passed. The initial + standalone tests passed, then Clippy found a test-only range predicate; + an equivalent range expression was applied and the final full scoped suite + and Clippy both passed. No decoder arithmetic or numerical gate was changed. +- Pinned C bridge oracle: **14 passed, 0 failed**, including five new tests and + all nine earlier tests byte preserved. The finite corpora's **146,276,352** + element comparisons, per-position coverage assertions, both unaligned batches + and all nonfinite classification/infinity-sign/zero cases passed. +- Bounded GGUF visitor: **9 passed, 0 failed**; both new formats' geometry guards, + two-chunk exact C bytes, source offsets, output byte receipts, malformed/truncated + input, callback failure stopping subsequent reads and nonfinite behavior passed. +- Control-plane library/test Clippy with warnings denied, formatting and diff + checks passed. All ten vendored GGML manifest hashes passed; production bridge + code, prior test functions and C compiler arithmetic flags are unchanged. +- The normal quant-crate dependency tree contains only `leleka-quant-core`. + Both owned temporary standalone build targets were removed; the separately + coordinated existing shared target cache was retained. + +No finite numeric mismatch occurred and no tolerance was relaxed. The NaN gate +compares classification rather than payload/sign equivalence. These results +apply to this CPU/compiler configuration. Linux/GCC, real-model quality, +complete inference and GPU qualification remain separate gates. -- 2.54.0