diff --git a/control-plane/src/ggml_bridge.rs b/control-plane/src/ggml_bridge.rs index 4a486c78..39d127e0 100644 --- a/control-plane/src/ggml_bridge.rs +++ b/control-plane/src/ggml_bridge.rs @@ -580,4 +580,277 @@ mod tests { } } } + + // Independent packed fixtures: all expectations come from the pinned C oracle, + // never from the Rust decoder/helper or a generated Rust value table. + fn synthetic_k_block(kind: u32, d: u16, dmin: u16, pattern: u32) -> Vec { + let bytes = if kind == 12 { 144 } else { 176 }; + let mut block = vec![0u8; bytes]; + block[..2].copy_from_slice(&d.to_le_bytes()); + block[2..4].copy_from_slice(&dmin.to_le_bytes()); + for (position, byte) in block[4..16].iter_mut().enumerate() { + *byte = (pattern as u8) + .wrapping_mul((position * 2 + 1) as u8) + .rotate_left((position % 8) as u32) + .wrapping_add((pattern >> 8) as u8); + } + let quant_start = if kind == 12 { 16 } else { 48 }; + for pair in 0..4 { + for lane in 0..32 { + let low = (lane + pattern as usize + pair) & 15; + let high = (31 - lane + (pattern as usize >> 4) + pair) & 15; + block[quant_start + pair * 32 + lane] = low as u8 | ((high as u8) << 4); + } + } + if kind == 13 { + for (lane, byte) in block[16..48].iter_mut().enumerate() { + *byte = (pattern >> 8) as u8 ^ if lane >= 16 { 0xff } else { 0 }; + } + } + block + } + + fn assert_k_c_reference(kind: u32, block: &[u8], finite: bool) -> [f32; 256] { + use leleka_quant_core::{q4_k, q5_k}; + let mut reference = [0.0; 256]; + decode_into(kind, block, &mut reference).unwrap(); + let actual = match kind { + 12 => q4_k::decode_block(block.try_into().unwrap()).unwrap(), + 13 => q5_k::decode_block(block.try_into().unwrap()).unwrap(), + _ => unreachable!(), + }; + for (element, (actual, reference)) in actual.iter().zip(&reference).enumerate() { + if finite { + assert!(actual.is_finite() && reference.is_finite()); + } + if reference.is_nan() { + assert!( + actual.is_nan(), + "kind={kind} element={element} block={block:?}" + ); + } else { + assert_eq!( + actual.to_bits(), + reference.to_bits(), + "kind={kind} element={element} block={block:?}" + ); + } + } + actual + } + + #[test] + fn pinned_ggml_q4_q5_k_exhaust_each_finite_fp16_scale_role_separately() { + for kind in [12, 13] { + for vary_min in [false, true] { + let mut compared = 0; + for bits in 0..=u16::MAX { + if bits & 0x7c00 == 0x7c00 { + continue; + } + let (d, dmin) = if vary_min { + (0xbc00, bits) + } else { + (bits, 0x3800) + }; + let block = synthetic_k_block(kind, d, dmin, u32::from(bits)); + assert_k_c_reference(kind, &block, true); + compared += 1; + } + assert_eq!(compared, 63_488, "kind={kind} min_role={vary_min}"); + } + } + } + + #[test] + fn pinned_ggml_q4_q5_k_packed_fields_and_subscale_positions_match_rust_bits() { + for kind in [12, 13] { + let mut packed_scales = [[false; 256]; 12]; + let mut scales = [[false; 64]; 8]; + let mut minima = [[false; 64]; 8]; + let mut packed_quants = [[false; 256]; 128]; + let mut high_bytes = [[false; 256]; 32]; + let mut codes = [[false; 32]; 256]; + let quant_start = if kind == 12 { 16 } else { 48 }; + for pattern in 0..=u16::MAX { + let block = synthetic_k_block(kind, 0x3555, 0xb800, u32::from(pattern)); + assert_k_c_reference(kind, &block, true); + for (position, byte) in block[4..16].iter().enumerate() { + packed_scales[position][usize::from(*byte)] = true; + } + for subblock in 0..8 { + let (scale, minimum) = if subblock < 4 { + (block[4 + subblock] & 63, block[8 + subblock] & 63) + } else { + ( + (block[8 + subblock] & 15) | ((block[subblock] >> 6) << 4), + (block[8 + subblock] >> 4) | ((block[4 + subblock] >> 6) << 4), + ) + }; + scales[subblock][usize::from(scale)] = true; + minima[subblock][usize::from(minimum)] = true; + } + for pair in 0..4 { + let mut low_seen = [false; 32]; + let mut high_seen = [false; 32]; + for lane in 0..32 { + let field = pair * 32 + lane; + let packed = block[quant_start + field]; + packed_quants[field][usize::from(packed)] = true; + let high = if kind == 13 { block[16 + lane] } else { 0 }; + if kind == 13 { + high_bytes[lane][usize::from(high)] = true; + } + let low_code = + (packed & 15) | if high & (1 << (pair * 2)) != 0 { 16 } else { 0 }; + let high_code = + (packed >> 4) | if high & (2 << (pair * 2)) != 0 { 16 } else { 0 }; + codes[pair * 64 + lane][usize::from(low_code)] = true; + codes[pair * 64 + lane + 32][usize::from(high_code)] = true; + low_seen[usize::from(low_code)] = true; + high_seen[usize::from(high_code)] = true; + } + let limit = if kind == 12 { 16 } else { 32 }; + assert!(low_seen[..limit].iter().all(|seen| *seen)); + assert!(high_seen[..limit].iter().all(|seen| *seen)); + } + } + assert!(packed_scales.iter().flatten().all(|seen| *seen)); + assert!(scales.iter().flatten().all(|seen| *seen)); + assert!(minima.iter().flatten().all(|seen| *seen)); + assert!(packed_quants.iter().flatten().all(|seen| *seen)); + let limit = if kind == 12 { 16 } else { 32 }; + assert!( + codes + .iter() + .all(|position| position[..limit].iter().all(|seen| *seen)) + ); + if kind == 13 { + assert!(high_bytes.iter().flatten().all(|seen| *seen)); + } + } + } + + #[test] + fn pinned_ggml_q4_q5_k_joint_finite_edges_and_exact_cancellation_match_rust_bits() { + let edges = [ + 0x0000u16, 0x8000, 0x0001, 0x8001, 0x03ff, 0x83ff, 0x0400, 0x8400, 0x3555, 0xb555, + 0x3800, 0xb800, 0x3bff, 0xbbff, 0x3c00, 0xbc00, 0x3c01, 0xbc01, 0x7bff, 0xfbff, + ]; + for kind in [12, 13] { + for (left, d) in edges.into_iter().enumerate() { + for (right, dmin) in edges.into_iter().enumerate() { + let block = + synthetic_k_block(kind, d, dmin, (left * 257 + right * 65_537) as u32); + assert_k_c_reference(kind, &block, true); + } + } + for d in edges { + let mut block = synthetic_k_block(kind, d, d, 0); + block[4..12].fill(1); + block[12..16].fill(0x11); + let quant_start = if kind == 12 { 16 } else { 48 }; + if kind == 13 { + block[16..48].fill(0); + } + block[quant_start..].fill(0x11); + let actual = assert_k_c_reference(kind, &block, true); + assert!(actual.iter().all(|value| value.to_bits() == 0)); + } + } + } + + #[test] + fn pinned_ggml_q4_q5_k_nonfinite_scale_roles_and_joint_edges_preserve_c_values() { + let special = [ + 0x0000u16, 0x8000, 0x3c00, 0xbc00, 0x7c00, 0xfc00, 0x7c01, 0xfc01, 0x7e00, 0xfe00, + ]; + for kind in [12, 13] { + for vary_min in [false, true] { + let mut compared = 0; + for bits in 0..=u16::MAX { + if bits & 0x7c00 != 0x7c00 { + continue; + } + let (d, dmin) = if vary_min { + (0x3c00, bits) + } else { + (bits, 0xbc00) + }; + let mut block = synthetic_k_block(kind, d, dmin, u32::from(bits)); + assert_k_c_reference(kind, &block, false); + // Explicit all-zero packed scale/minimum/quant values exercise + // Inf*zero and downstream subtraction instead of assuming Inf. + block[4..].fill(0); + assert_k_c_reference(kind, &block, false); + compared += 1; + } + assert_eq!(compared, 2_048); + } + for (left, d) in special.into_iter().enumerate() { + for (right, dmin) in special.into_iter().enumerate() { + let block = + synthetic_k_block(kind, d, dmin, (left * 257 + right * 65_537) as u32); + assert_k_c_reference(kind, &block, false); + } + } + } + } + + #[test] + fn pinned_ggml_q4_q5_k_aligned_unaligned_bulk_and_shape_contracts_match_rust() { + use leleka_quant_core::{q4_k, q5_k}; + let edges = [ + 0x0000u16, 0x8000, 0x0001, 0x8001, 0x03ff, 0x83ff, 0x0400, 0x8400, 0x3555, 0xb555, + 0x3800, 0xb800, 0x3c00, 0xbc00, 0x7bff, 0xfbff, + ]; + for (kind, block_bytes) in [(12, q4_k::BLOCK_BYTES), (13, q5_k::BLOCK_BYTES)] { + for unaligned in [false, true] { + let mut storage = vec![0u8; edges.len() * block_bytes + 16]; + let start = storage.as_ptr().align_offset(16) + usize::from(unaligned); + let source = &mut storage[start..start + edges.len() * block_bytes]; + assert_eq!( + source.as_ptr().align_offset(16), + if unaligned { 15 } else { 0 } + ); + for (number, d) in edges.into_iter().enumerate() { + source[number * block_bytes..(number + 1) * block_bytes].copy_from_slice( + &synthetic_k_block( + kind, + d, + edges[(number * 7 + 3) % edges.len()], + number as u32 * 65_537, + ), + ); + } + let mut reference = vec![0.0; edges.len() * 256]; + let mut actual = vec![0.0; reference.len()]; + decode_into(kind, source, &mut reference).unwrap(); + if kind == 12 { + q4_k::decode_into(source, &mut actual).unwrap(); + } else { + q5_k::decode_into(source, &mut actual).unwrap(); + } + for (actual, reference) in actual.iter().zip(&reference) { + assert_eq!(actual.to_bits(), reference.to_bits()); + } + for (input_len, output_len) in [ + (source.len() - 1, actual.len()), + (source.len(), actual.len() - 1), + (source.len(), actual.len() + 1), + ] { + let mut output = vec![123.0; output_len]; + let result = if kind == 12 { + q4_k::decode_into(&source[..input_len], &mut output) + } else { + q5_k::decode_into(&source[..input_len], &mut output) + }; + assert!(result.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)); + } + } + } + } } diff --git a/control-plane/src/gguf_f32_stream.rs b/control-plane/src/gguf_f32_stream.rs index 016fe18c..973e8af0 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, iq4_xs, q8_0}; +use leleka_quant_core::{iq4_nl, iq4_xs, q4_k, q5_k, q8_0}; use crate::{ggml_bridge, gguf, iq3_s, kar_codec}; @@ -27,6 +27,8 @@ where .ok_or_else(|| format!("unsupported GGUF source kind {source_kind}"))?; let rust_geometry = match source_kind { 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")), 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, @@ -83,6 +85,22 @@ where } callback(source, &derived)?; } + 12 => { + for block in source.as_chunks::<{ q4_k::BLOCK_BYTES }>().0 { + for value in q4_k::decode_block(block)? { + derived.extend_from_slice(&value.to_le_bytes()); + } + } + callback(source, &derived)?; + } + 13 => { + for block in source.as_chunks::<{ q5_k::BLOCK_BYTES }>().0 { + for value in q5_k::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)? { @@ -502,4 +520,186 @@ mod tests { ); } } + + #[test] + fn q4_q5_k_streams_preserve_bounded_c_bytes_offsets_receipts_and_failure_semantics() { + let edges = [ + 0x0000u16, 0x8000, 0x0001, 0x83ff, 0x0400, 0x3555, 0xbc00, 0x7bff, + ]; + for kind in [12, 13] { + 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]; + block[..2].copy_from_slice(&edges[number % edges.len()].to_le_bytes()); + block[2..4].copy_from_slice(&edges[(number * 7 + 3) % edges.len()].to_le_bytes()); + for (position, byte) in block[4..].iter_mut().enumerate() { + *byte = (number * 17 + position * 29) as u8; + } + 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 = 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 q4_q5_k_streams_preserve_both_nonfinite_scale_roles_and_zero_packed_fields() { + let scales = [ + 0x0000u16, 0x8000, 0x3c00, 0xbc00, 0x7c00, 0xfc00, 0x7c01, 0xfc01, 0x7e00, 0xfe00, + ]; + for kind in [12, 13] { + let (elements, bytes) = gguf::block_geometry(kind).unwrap(); + for d in scales { + for dmin in scales { + for zero_fields in [false, true] { + let mut block = vec![0u8; bytes as usize]; + block[..2].copy_from_slice(&d.to_le_bytes()); + block[2..4].copy_from_slice(&dmin.to_le_bytes()); + if !zero_fields { + for (position, byte) in block[4..].iter_mut().enumerate() { + *byte = (position * 29 + 17) 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); + 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); + } + } + } + } + } } diff --git a/crates/quant-core/README.md b/crates/quant-core/README.md index 3f158be4..5eefcade 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, IQ4_NL, IQ4_XS and Q8_0 CPU decoding and binary16-to-binary32 +`leleka-quant-core` provides IQ3_S, IQ4_NL, IQ4_XS, Q4_K, Q5_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. @@ -64,6 +64,30 @@ 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. +Q4_K accepts 144-byte blocks; Q5_K accepts 176-byte blocks. Both produce 256 +values from a little-endian FP16 scale and minimum, a shared 12-byte packed +six-bit scale/minimum header, and eight 32-element subblocks. The crate-private +header helper follows pinned `get_scale_min_k4`: the upper two bits for subblocks +4–7 share the first eight header bytes, and the remaining four bytes store their +low nibbles. Q4_K's quant bytes start at offset 16 and split each byte into two +32-element halves. Q5_K's 32 high-bit bytes start at offset 16 and low-nibble +bytes at offset 48; every high-bit lane is reused across four pairs, with masks +1/2, 4/8, 16/32 and 64/128 selecting the corresponding half. + +The arithmetic follows pinned `dequantize_row_q4_K` / `dequantize_row_q5_K`: +first form `d * scale` and `dmin * minimum`, then compute +`subblock_scale * quant - subblock_minimum`. These steps are kept separate, with +no `mul_add` or reassociation. Both formats admit all FP16 encodings, preserving +signed zero, infinity times zero and infinity-minus-infinity NaN behavior; +consumer value policies remain unchanged. Like the other bulk APIs, invalid +shapes fail before output writes, empty input/output is valid, and decoding uses +no heap allocation or source alignment requirement. Synthetic standalone tests +check independently specified wire bytes/expected values, both scale-header +branches, all Q5 high masks, bulk/shape handling and nonfinite/signed-zero cases. +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. + 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/k_scale_min.rs b/crates/quant-core/src/k_scale_min.rs new file mode 100644 index 00000000..7d71df9d --- /dev/null +++ b/crates/quant-core/src/k_scale_min.rs @@ -0,0 +1,44 @@ +//! Crate-private Q4_K/Q5_K six-bit scale/minimum unpacking. Mirrors +//! `get_scale_min_k4` at llama.cpp 3cf03257f219afbe7334045ff7c6a06ac68c627d. +//! Original GGML source is MIT licensed; see ../LICENSE-GGML. + +/// `subblock` is one of the eight 32-element subblocks in a complete K block. +pub(crate) fn scale_min(scales: &[u8; 12], subblock: usize) -> (u8, u8) { + if subblock < 4 { + (scales[subblock] & 63, scales[subblock + 4] & 63) + } else { + ( + (scales[subblock + 4] & 15) | ((scales[subblock - 4] >> 6) << 4), + (scales[subblock + 4] >> 4) | ((scales[subblock] >> 6) << 4), + ) + } +} + +#[cfg(test)] +mod tests { + use super::scale_min; + + #[test] + fn independent_packed_bytes_cover_both_scale_minimum_branches() { + let packed = [ + 0x41, 0x82, 0xc3, 0x04, 0x45, 0x86, 0xc7, 0x08, 0x21, 0x43, 0x65, 0x87, + ]; + let expected = [ + (1, 5), + (2, 6), + (3, 7), + (4, 8), + (17, 18), + (35, 36), + (53, 54), + (7, 8), + ]; + for (subblock, pair) in expected.into_iter().enumerate() { + assert_eq!(scale_min(&packed, subblock), pair); + } + for subblock in 0..8 { + assert_eq!(scale_min(&[0; 12], subblock), (0, 0)); + assert_eq!(scale_min(&[255; 12], subblock), (63, 63)); + } + } +} diff --git a/crates/quant-core/src/lib.rs b/crates/quant-core/src/lib.rs index 0004f293..9e16b8a8 100644 --- a/crates/quant-core/src/lib.rs +++ b/crates/quant-core/src/lib.rs @@ -5,6 +5,9 @@ pub mod iq3_s; mod iq3s_grid; pub mod iq4_nl; pub mod iq4_xs; +mod k_scale_min; +pub mod q4_k; +pub mod q5_k; pub mod q8_0; pub fn f16_bits_to_f32(bits: u16) -> f32 { diff --git a/crates/quant-core/src/q4_k.rs b/crates/quant-core/src/q4_k.rs new file mode 100644 index 00000000..2e9f6e14 --- /dev/null +++ b/crates/quant-core/src/q4_k.rs @@ -0,0 +1,185 @@ +//! Allocation-free CPU decoding of GGML Q4_K blocks (256 values / 144 bytes). +//! Layout and arithmetic follow llama.cpp 3cf03257f219afbe7334045ff7c6a06ac68c627d +//! `dequantize_row_q4_K` / `block_q4_K` (MIT, ggml authors; ../LICENSE-GGML). +//! All FP16 encodings are admitted; consumers retain their nonfinite policy. + +use crate::{f16_bits_to_f32, k_scale_min::scale_min}; + +pub const BLOCK_BYTES: usize = 144; +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[0], block[1]])); + let minimum = f16_bits_to_f32(u16::from_le_bytes([block[2], block[3]])); + let scales: &[u8; 12] = block[4..16].try_into().expect("fixed Q4_K scale header"); + let mut output = [0.0; BLOCK_ELEMENTS]; + for pair in 0..4 { + let (s1, m1) = scale_min(scales, 2 * pair); + let (s2, m2) = scale_min(scales, 2 * pair + 1); + let d1 = base * f32::from(s1); + let min1 = minimum * f32::from(m1); + let d2 = base * f32::from(s2); + let min2 = minimum * f32::from(m2); + for lane in 0..32 { + let packed = block[16 + 32 * pair + lane]; + // Preserve the C intermediate products and final subtraction. + output[64 * pair + lane] = d1 * f32::from(packed & 15) - min1; + output[64 * pair + lane + 32] = d2 * f32::from(packed >> 4) - min2; + } + } + Ok(output) +} + +/// Shape errors leave all output untouched. Empty slices form a zero-block +/// operation; arbitrary source alignment is supported without a 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("Q4_K 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() -> [u8; BLOCK_BYTES] { + let mut block = [0u8; BLOCK_BYTES]; + block[..4].copy_from_slice(&[0x00, 0x38, 0x00, 0x34]); // d=0.5, dmin=0.25 + block[4..16].copy_from_slice(&[ + 0x41, 0x82, 0xc3, 0x04, 0x45, 0x86, 0xc7, 0x08, 0x21, 0x43, 0x65, 0x87, + ]); + for pair in 0..4 { + for lane in 0..32 { + block[16 + 32 * pair + lane] = (lane % 16) as u8 | (((15 - lane % 16) as u8) << 4); + } + } + block + } + + #[test] + fn independent_wire_values_cover_scale_minimum_and_split_halves() { + let actual = decode_block(&known_block()).unwrap(); + let scale = [0.5f32, 1.0, 1.5, 2.0, 8.5, 17.5, 26.5, 3.5]; + let minimum = [1.25f32, 1.5, 1.75, 2.0, 4.5, 9.0, 13.5, 2.0]; + for subblock in 0..8 { + for lane in 0..32 { + let quant = if subblock % 2 == 0 { + lane % 16 + } else { + 15 - lane % 16 + } as f32; + assert_eq!( + actual[32 * subblock + lane].to_bits(), + (scale[subblock] * quant - minimum[subblock]).to_bits() + ); + } + } + assert_eq!(actual[0], -1.25); + assert_eq!(actual[32], 13.5); + assert_eq!(actual[160], 253.5); + assert_eq!(actual[224], 50.5); + } + + #[test] + fn bulk_unaligned_and_bad_shapes_preserve_output_contract() { + let block = known_block(); + 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(); + assert_eq!(&output[..BLOCK_ELEMENTS], &expected); + assert_eq!(&output[BLOCK_ELEMENTS..], &expected); + 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_arithmetic_is_admitted() { + let mut block = [0u8; BLOCK_BYTES]; + block[4..16].copy_from_slice(&[1, 1, 1, 1, 1, 1, 1, 1, 0x11, 0x11, 0x11, 0x11]); + block[16..].fill(0x11); + for (d, min, expected) in [ + (0u16, 0u16, 0u32), + (0x8000, 0, 0x8000_0000), + (0, 0x8000, 0), + (0x8000, 0x8000, 0), + ] { + block[..2].copy_from_slice(&d.to_le_bytes()); + block[2..4].copy_from_slice(&min.to_le_bytes()); + assert!( + decode_block(&block) + .unwrap() + .iter() + .all(|v| v.to_bits() == expected) + ); + } + for (d, min, expected_sign) in [ + (0x7c00u16, 0x3c00u16, false), + (0xfc00, 0x3c00, true), + (0x3c00, 0x7c00, true), + (0x3c00, 0xfc00, false), + ] { + block[..2].copy_from_slice(&d.to_le_bytes()); + block[2..4].copy_from_slice(&min.to_le_bytes()); + let mut output = [0.0; BLOCK_ELEMENTS]; + decode_into(&block, &mut output).unwrap(); + assert!( + output + .iter() + .all(|v| v.is_infinite() && v.is_sign_negative() == expected_sign) + ); + } + for (d, min) in [ + (0x7c00u16, 0x7c00u16), + (0xfc00, 0xfc00), + (0x7c01, 0x3c00), + (0x3c00, 0xfc01), + ] { + block[..2].copy_from_slice(&d.to_le_bytes()); + block[2..4].copy_from_slice(&min.to_le_bytes()); + assert!(decode_block(&block).unwrap().iter().all(|v| v.is_nan())); + } + block[..2].copy_from_slice(&0x7c00u16.to_le_bytes()); + block[2..4].fill(0); + block[16..].fill(0); // Infinity times quant zero. + assert!(decode_block(&block).unwrap().iter().all(|v| v.is_nan())); + block[16..].fill(0x11); + block[4..16].fill(0); // Infinity times scale zero. + assert!(decode_block(&block).unwrap().iter().all(|v| v.is_nan())); + block[..2].copy_from_slice(&0x3c00u16.to_le_bytes()); + block[2..4].copy_from_slice(&0x7c00u16.to_le_bytes()); // Infinite minimum times zero. + assert!(decode_block(&block).unwrap().iter().all(|v| v.is_nan())); + } +} diff --git a/crates/quant-core/src/q5_k.rs b/crates/quant-core/src/q5_k.rs new file mode 100644 index 00000000..e0b117ee --- /dev/null +++ b/crates/quant-core/src/q5_k.rs @@ -0,0 +1,207 @@ +//! Allocation-free CPU decoding of GGML Q5_K blocks (256 values / 176 bytes). +//! Layout and arithmetic follow llama.cpp 3cf03257f219afbe7334045ff7c6a06ac68c627d +//! `dequantize_row_q5_K` / `block_q5_K` (MIT, ggml authors; ../LICENSE-GGML). +//! All FP16 encodings are admitted; consumers retain their nonfinite policy. + +use crate::{f16_bits_to_f32, k_scale_min::scale_min}; + +pub const BLOCK_BYTES: usize = 176; +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[0], block[1]])); + let minimum = f16_bits_to_f32(u16::from_le_bytes([block[2], block[3]])); + let scales: &[u8; 12] = block[4..16].try_into().expect("fixed Q5_K scale header"); + let mut output = [0.0; BLOCK_ELEMENTS]; + for pair in 0..4 { + let (s1, m1) = scale_min(scales, 2 * pair); + let (s2, m2) = scale_min(scales, 2 * pair + 1); + let d1 = base * f32::from(s1); + let min1 = minimum * f32::from(m1); + let d2 = base * f32::from(s2); + let min2 = minimum * f32::from(m2); + let low_mask = 1u8 << (2 * pair); + let high_mask = 2u8 << (2 * pair); + for lane in 0..32 { + let packed = block[48 + 32 * pair + lane]; + // The same high-bit lane is reused across all four 64-value pairs; + // each pair selects a different bit for each 32-element half. + let high = block[16 + lane]; + let low_quant = (packed & 15) + if high & low_mask != 0 { 16 } else { 0 }; + let high_quant = (packed >> 4) + if high & high_mask != 0 { 16 } else { 0 }; + output[64 * pair + lane] = d1 * f32::from(low_quant) - min1; + output[64 * pair + lane + 32] = d2 * f32::from(high_quant) - min2; + } + } + Ok(output) +} + +/// Shape errors leave all output untouched. Empty slices form a zero-block +/// operation; arbitrary source alignment is supported without a 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("Q5_K 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() -> [u8; BLOCK_BYTES] { + let mut block = [0u8; BLOCK_BYTES]; + block[..4].copy_from_slice(&[0x00, 0x38, 0x00, 0x34]); // d=0.5, dmin=0.25 + block[4..16].copy_from_slice(&[ + 0x41, 0x82, 0xc3, 0x04, 0x45, 0x86, 0xc7, 0x08, 0x21, 0x43, 0x65, 0x87, + ]); + for lane in 0..32 { + block[16 + lane] = 1 << (lane % 8); + } + for pair in 0..4 { + for lane in 0..32 { + block[48 + 32 * pair + lane] = (lane % 16) as u8 | (((15 - lane % 16) as u8) << 4); + } + } + block + } + + #[test] + fn independent_wire_values_cover_scale_minimum_nibbles_and_high_masks() { + let actual = decode_block(&known_block()).unwrap(); + let scale = [0.5f32, 1.0, 1.5, 2.0, 8.5, 17.5, 26.5, 3.5]; + let minimum = [1.25f32, 1.5, 1.75, 2.0, 4.5, 9.0, 13.5, 2.0]; + for subblock in 0..8 { + for lane in 0..32 { + let nibble = if subblock % 2 == 0 { + lane % 16 + } else { + 15 - lane % 16 + }; + let high = if lane % 8 == subblock { 16 } else { 0 }; + let expected = scale[subblock] * (nibble + high) as f32 - minimum[subblock]; + assert_eq!(actual[32 * subblock + lane].to_bits(), expected.to_bits()); + } + } + assert_eq!(actual[0], 6.75); + assert_eq!(actual[33], 28.5); + assert_eq!(actual[71], 8.75); + assert_eq!(actual[255], 54.0); + } + + #[test] + fn each_high_bit_maps_only_to_its_32_element_subblock() { + let mut block = [0u8; BLOCK_BYTES]; + block[..2].copy_from_slice(&0x3c00u16.to_le_bytes()); + block[4..16].copy_from_slice(&[1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1]); + for bit in 0..8 { + block[16..48].fill(1 << bit); + let actual = decode_block(&block).unwrap(); + for (element, value) in actual.into_iter().enumerate() { + assert_eq!(value, if element / 32 == bit { 16.0 } else { 0.0 }); + } + } + } + + #[test] + fn bulk_unaligned_and_bad_shapes_preserve_output_contract() { + let block = known_block(); + 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(); + assert_eq!(&output[..BLOCK_ELEMENTS], &expected); + assert_eq!(&output[BLOCK_ELEMENTS..], &expected); + 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_arithmetic_is_admitted() { + let mut block = [0u8; BLOCK_BYTES]; + block[4..16].copy_from_slice(&[1, 1, 1, 1, 1, 1, 1, 1, 0x11, 0x11, 0x11, 0x11]); + block[48..].fill(0x11); + for (d, min, expected) in [ + (0u16, 0u16, 0u32), + (0x8000, 0, 0x8000_0000), + (0, 0x8000, 0), + (0x8000, 0x8000, 0), + ] { + block[..2].copy_from_slice(&d.to_le_bytes()); + block[2..4].copy_from_slice(&min.to_le_bytes()); + assert!( + decode_block(&block) + .unwrap() + .iter() + .all(|v| v.to_bits() == expected) + ); + } + for (d, min, expected_sign) in [ + (0x7c00u16, 0x3c00u16, false), + (0xfc00, 0x3c00, true), + (0x3c00, 0x7c00, true), + (0x3c00, 0xfc00, false), + ] { + block[..2].copy_from_slice(&d.to_le_bytes()); + block[2..4].copy_from_slice(&min.to_le_bytes()); + let mut output = [0.0; BLOCK_ELEMENTS]; + decode_into(&block, &mut output).unwrap(); + assert!( + output + .iter() + .all(|v| v.is_infinite() && v.is_sign_negative() == expected_sign) + ); + } + for (d, min) in [ + (0x7c00u16, 0x7c00u16), + (0xfc00, 0xfc00), + (0x7c01, 0x3c00), + (0x3c00, 0xfc01), + ] { + block[..2].copy_from_slice(&d.to_le_bytes()); + block[2..4].copy_from_slice(&min.to_le_bytes()); + assert!(decode_block(&block).unwrap().iter().all(|v| v.is_nan())); + } + block[..2].copy_from_slice(&0x7c00u16.to_le_bytes()); + block[2..4].fill(0); + block[48..].fill(0); // Infinity times quant zero. + assert!(decode_block(&block).unwrap().iter().all(|v| v.is_nan())); + block[48..].fill(0x11); + block[4..16].fill(0); // Infinity times scale zero. + assert!(decode_block(&block).unwrap().iter().all(|v| v.is_nan())); + block[..2].copy_from_slice(&0x3c00u16.to_le_bytes()); + block[2..4].copy_from_slice(&0x7c00u16.to_le_bytes()); // Infinite minimum times zero. + assert!(decode_block(&block).unwrap().iter().all(|v| v.is_nan())); + } +} diff --git a/docs/q4-q5-k-reference-parity.md b/docs/q4-q5-k-reference-parity.md new file mode 100644 index 00000000..bfd695af --- /dev/null +++ b/docs/q4-q5-k-reference-parity.md @@ -0,0 +1,120 @@ +# Q4_K / Q5_K CPU reference parity + +This port implements GGUF kind 12 (Q4_K) and kind 13 (Q5_K) preparation decoding +in the independent standard-library-only Rust quant crate. It does not replace +the complete engine or prove model/GPU readiness. Other preparation formats still +use the legacy C decoder. No model weights, request data or user experiments are +read by these gates. + +## Pinned layout and arithmetic + +The oracle is actual output from the unmodified vendored GGML C decoder at +llama.cpp `3cf03257f219afbe7334045ff7c6a06ac68c627d`, also pinned by imported +Strata `d9ab8435f654c368c586340d490915f6addf56a3`. The source hashes and original +MIT license remain in [GGML provenance](../control-plane/third_party/ggml/UPSTREAM.md) +and [the quant crate notice](../crates/quant-core/LICENSE-GGML). +The production C bridge, prior fourteen oracle tests and compiler arithmetic +flags remain unchanged. + +Both formats output 256 values and have two independent little-endian FP16 +header values: `d` at bytes 0–1 and `dmin` at 2–3. Twelve packed scale/minimum +bytes occupy 4–15. Q4_K is 144 bytes with four 32-byte nibble groups at 16–143. +Q5_K is 176 bytes with a shared 32-byte high-bit bank at 16–47 and nibble groups +at 48–175. Each pair produces two consecutive 32-element halves. The Q5 bank +reuses each lane byte with masks 1/2, 4/8, 16/32 and 64/128 across the four pairs. +Six-bit scale/minimum unpacking preserves the different lower/upper field +locations for subblocks 0–3 and 4–7. + +The arithmetic retains separate operations in C order: `d * subscale`, +`dmin * subminimum`, then `scaled_d * quant - scaled_minimum`. The Rust code does +not use `mul_add`; this gate does not change C contraction or fast-math flags. +All FP16 header encodings are admitted, preserving the old C value policy. +Infinity multiplied by zero and infinity subtraction can yield NaN. Shape +errors leave caller output untouched; downstream consumers keep their own +value policies. Signed-zero output bits are part of finite parity; NaN payload +or sign equivalence is not claimed. + +## Independent coverage + +Expected numerical output always comes from the pinned C decoder, never from +the new Rust implementation or its packed-scale helper. Generated bytes and +coverage bookkeeping are independent of those production functions. + +- For each format, every one of the **63,488 finite FP16 encodings** is exercised + separately in the `d` role with `dmin=0.5` and the `dmin` role with `d=-1`. + These sweeps contribute **65,011,712** exact element comparisons across the + two formats and roles. They do not exhaust both FP16 values jointly. +- Each format separately compares **65,536 independently generated packed + patterns** with fixed finite scales. Assertions require every byte value at + every packed scale/minimum field and quant field; every six-bit subscale and + minimum at every one of eight positions; every quant code at every output + position; and, for Q5_K, every byte value at each high-bank lane. Each block + additionally covers all 16 Q4 codes or 32 Q5 codes in each output half. These + cases contribute **33,554,432** comparisons. +- A **20×20** joint finite boundary matrix includes positive/negative zero, + signed minimum/largest subnormals, normal boundaries, adjacent-to-one values + and maximum finite values. Twenty further equal-scale fixtures per format + explicitly require exact cancellation to positive zero. These contribute + **215,040** comparisons. +- Sixteen-block boundary batches per format run with both 16-byte aligned and + deliberately unaligned inputs through both bulk APIs, adding **16,384** + comparisons. Invalid input/output lengths must reject before changing any + sentinel output, for both the Rust and C APIs. +- Every **2,048 nonfinite FP16 encoding** is exercised in each header role for + each format with independently packed fields and explicit all-zero packed + fields. A **10×10** joint matrix includes finite, zero, infinity and NaN + headers. NaN classification must agree and every non-NaN output must match + exact bits, including infinity signs and any finite zero. + +All finite gates use exact `f32::to_bits()` equality and zero tolerance. +The finite corpus contributes **98,797,568** comparisons. It does not exhaust +all 63,488² finite header pairs, all combinations of packed fields, or every +scale/code combination at every header pair. + +## Bounded visitor + +Only kinds 12 and 13 gain new Rust routes. Their decoder/metadata geometry must +agree before seek; other format branches and the source cap remain unchanged. +A synthetic tensor per format crosses two callbacks, verifying the actual C +bytes, exact source offsets, total F32 byte receipt and bounded source/derived +slices. Empty/misaligned shapes reject before seek or callback; first/late +truncation never delivers a partial chunk; callback failure at either callback +stops later reads. Nonfinite joint headers and zero packed fields retain C +classification and all non-NaN output bits. Previous nine visitor tests remain. + +```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`), with unchanged C build + flags and no arithmetic tolerance or contraction-policy changes. +- Standalone quant crate: **20 passed, 0 failed** (eight new helper/Q4_K/Q5_K + tests). All-target Clippy with warnings denied and owned-file formatting passed. + The owned temporary target was cleaned and removed. +- Pinned C oracle: **19 passed, 0 failed**, including five new tests and all + fourteen prior tests byte preserved. All **98,797,568** new finite exact-bit + comparisons, every packed/subscale/minimum/code position coverage assertion, + both nonfinite header roles, explicit zero fields, joint edge matrices, + cancellation, aligned/unaligned bulk and shape-sentinel gates passed. +- Visitor: **11 passed, 0 failed**, including two new tests and all nine prior + visitor test functions byte preserved. Q4_K used source chunks 28,080/2,448 + bytes and F32 chunks 199,680/17,408 bytes; Q5_K used 28,160/2,992 and + 163,840/17,408 bytes. Offsets, receipts, all shape/truncation/callback gates + and nonfinite header/zero-field behavior passed. +- Control-plane library/test Clippy with warnings denied, formatting, diff and + all ten vendored GGML manifest hash checks passed. The production bridge and + C source remain unchanged; normal quant-crate dependency tree is crate-only. + The existing coordinated shared target cache was retained. + +No finite mismatch was observed and no quality gate or tolerance was weakened. +NaN payload/sign equivalence is outside this classification contract. These +results apply to this CPU/compiler configuration; Linux/GCC qualification, +actual model/GPU inference, model quality and performance remain separate. +