From a498381cb7c34a73b338135ab9a9de63b8134f33 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Wed, 7 Oct 2026 20:53:25 +0200 Subject: [PATCH] refactor(model): extract independent Rust IQ3 decoding core --- Cargo.lock | 9 ++ Cargo.toml | 4 +- control-plane/Cargo.toml | 1 + control-plane/src/ggml_bridge.rs | 129 ++++++++++++++++++ control-plane/src/kar_codec.rs | 17 +-- control-plane/src/lib.rs | 3 +- crates/quant-core/Cargo.toml | 14 ++ crates/quant-core/LICENSE-GGML | 21 +++ crates/quant-core/README.md | 46 +++++++ .../quant-core}/src/iq3_s.rs | 2 +- .../quant-core}/src/iq3s_grid.rs | 2 +- crates/quant-core/src/lib.rs | 48 +++++++ docs/iq3-reference-parity.md | 63 +++++++++ scripts/check-local.sh | 3 + 14 files changed, 340 insertions(+), 22 deletions(-) create mode 100644 crates/quant-core/Cargo.toml create mode 100644 crates/quant-core/LICENSE-GGML create mode 100644 crates/quant-core/README.md rename {control-plane => crates/quant-core}/src/iq3_s.rs (98%) rename {control-plane => crates/quant-core}/src/iq3s_grid.rs (98%) create mode 100644 crates/quant-core/src/lib.rs create mode 100644 docs/iq3-reference-parity.md diff --git a/Cargo.lock b/Cargo.lock index 071adc05..012e11e4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1014,6 +1014,14 @@ dependencies = [ "sha2", ] +[[package]] +name = "leleka-quant-core" +version = "0.1.0" +dependencies = [ + "hex", + "sha2", +] + [[package]] name = "leleka-tokenizer" version = "0.1.0" @@ -2013,6 +2021,7 @@ dependencies = [ "http-body-util", "jsonschema", "leleka-model-format", + "leleka-quant-core", "leleka-tokenizer", "libc", "regex", diff --git a/Cargo.toml b/Cargo.toml index 582be906..fb3b10fe 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,7 +1,7 @@ [workspace] resolver = "3" -members = ["crates/backend-api", "crates/tokenizer", "crates/model-format", "control-plane", "desktop-core"] -default-members = ["crates/backend-api", "crates/tokenizer", "crates/model-format", "control-plane", "desktop-core"] +members = ["crates/backend-api", "crates/tokenizer", "crates/model-format", "crates/quant-core", "control-plane", "desktop-core"] +default-members = ["crates/backend-api", "crates/tokenizer", "crates/model-format", "crates/quant-core", "control-plane", "desktop-core"] [workspace.package] edition = "2024" diff --git a/control-plane/Cargo.toml b/control-plane/Cargo.toml index 4a5fd3f3..e4454078 100644 --- a/control-plane/Cargo.toml +++ b/control-plane/Cargo.toml @@ -15,6 +15,7 @@ futures-core = "0.3" hex = "0.4" leleka-tokenizer = { path = "../crates/tokenizer" } leleka-model-format = { path = "../crates/model-format" } +leleka-quant-core = { path = "../crates/quant-core" } http-body = "1" jsonschema = { version = "0.58.4", default-features = false } libc = "0.2" diff --git a/control-plane/src/ggml_bridge.rs b/control-plane/src/ggml_bridge.rs index 797e31ed..d18c2fa1 100644 --- a/control-plane/src/ggml_bridge.rs +++ b/control-plane/src/ggml_bridge.rs @@ -91,6 +91,135 @@ mod tests { assert_eq!(decoded, iq3_s::decode_block(&block).unwrap()); } + // Generated packed fields only: no model weights, captures or external RNG. + // Each scale gets a reproducible field pattern independent of either decoder. + fn synthetic_iq3_block(scale_bits: u16, pattern: u32) -> [u8; iq3_s::BLOCK_BYTES] { + let mut block = [0u8; iq3_s::BLOCK_BYTES]; + block[..2].copy_from_slice(&scale_bits.to_le_bytes()); + let low = pattern as u8; + let high = pattern >> 8; + for (field, byte) in block[2..].iter_mut().enumerate() { + // For any fixed high byte, odd multiplication, rotation and addition + // form a bijection of all 256 low-byte values at every field position. + let odd = (2 * field + 1) as u8; + let salt = high + .wrapping_mul(0x85eb_ca6b) + .wrapping_add((field as u32).wrapping_mul(0x9e37_79b9)); + *byte = low + .wrapping_mul(odd) + .rotate_left((field % 8) as u32) + .wrapping_add((salt ^ (salt >> 16)) as u8); + } + block + } + + fn assert_exact_iq3_bits(block: &[u8; iq3_s::BLOCK_BYTES], case: u32) { + let mut reference = [0.0f32; iq3_s::BLOCK_ELEMENTS]; + decode_into(21, block, &mut reference).unwrap(); + let actual = iq3_s::decode_block(block).unwrap(); + let scale_bits = u16::from_le_bytes([block[0], block[1]]); + 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(), + "case={case} scale_bits={scale_bits:#06x} element={element} block={block:?}" + ); + } + } + + #[test] + fn pinned_ggml_iq3_matches_rust_bits_for_every_finite_fp16_scale() { + // Exhaust all 63,488 finite binary16 encodings, including both signed + // zeros, every subnormal/normal and both signs of the maximum finite. + let mut low_fields = [[false; 256]; 64]; + let mut high_fields = [[false; 256]; 8]; + let mut sign_fields = [[false; 256]; 32]; + let mut scale_nibbles = [[false; 16]; 8]; + let mut grid_indexes = [false; 512]; + let mut compared = 0; + for scale_bits in 0..=u16::MAX { + if scale_bits & 0x7c00 == 0x7c00 { + continue; + } + let block = synthetic_iq3_block(scale_bits, u32::from(scale_bits)); + assert_exact_iq3_bits(&block, u32::from(scale_bits)); + for (field, value) in block[2..66].iter().enumerate() { + low_fields[field][usize::from(*value)] = true; + } + for (field, value) in block[66..74].iter().enumerate() { + high_fields[field][usize::from(*value)] = true; + } + for (field, value) in block[74..106].iter().enumerate() { + sign_fields[field][usize::from(*value)] = true; + } + for subblock in 0..8 { + let nibble = (block[106 + subblock / 2] >> (4 * (subblock % 2))) & 15; + scale_nibbles[subblock][usize::from(nibble)] = true; + for part in 0..8 { + let grid = usize::from(block[2 + 8 * subblock + part]) + | (usize::from((block[66 + subblock] >> part) & 1) << 8); + grid_indexes[grid] = true; + } + } + compared += 1; + } + assert_eq!(compared, 63_488); + assert!(low_fields.iter().flatten().all(|seen| *seen)); + assert!(high_fields.iter().flatten().all(|seen| *seen)); + assert!(sign_fields.iter().flatten().all(|seen| *seen)); + assert!(scale_nibbles.iter().flatten().all(|seen| *seen)); + assert!(grid_indexes.iter().all(|seen| *seen)); + } + + #[test] + fn pinned_ggml_iq3_batch_bits_match_rust_with_unaligned_source() { + let scales = [ + 0x0000, 0x8000, 0x0001, 0x8001, 0x03ff, 0x83ff, 0x0400, 0x8400, 0x3555, 0xb555, 0x3c00, + 0xbc00, 0x7bff, 0xfbff, + ]; + let length = scales.len() * iq3_s::BLOCK_BYTES; + let mut storage = vec![0u8; length + 16]; + let start = storage.as_ptr().align_offset(16) + 1; + let source = &mut storage[start..start + length]; + assert_eq!(source.as_ptr().align_offset(16), 15); + for (number, scale) in scales.into_iter().enumerate() { + let block = synthetic_iq3_block(scale, number as u32 + 70_000); + source[number * iq3_s::BLOCK_BYTES..(number + 1) * iq3_s::BLOCK_BYTES] + .copy_from_slice(&block); + } + let mut reference = vec![0.0f32; scales.len() * iq3_s::BLOCK_ELEMENTS]; + let mut actual = vec![0.0f32; reference.len()]; + decode_into(21, source, &mut reference).unwrap(); + iq3_s::decode_into(source, &mut actual).unwrap(); + for (element, (actual, reference)) in actual.iter().zip(&reference).enumerate() { + assert_eq!( + actual.to_bits(), + reference.to_bits(), + "batch element={element}" + ); + } + } + + #[test] + fn independent_rust_iq3_refuses_every_nonfinite_fp16_scale() { + // GGML may decode these; Rust's existing refusal is deliberately retained. + let mut rejected = 0; + for scale_bits in 0..=u16::MAX { + if scale_bits & 0x7c00 != 0x7c00 { + continue; + } + let block = synthetic_iq3_block(scale_bits, u32::from(scale_bits)); + assert_eq!( + iq3_s::decode_block(&block).unwrap_err(), + "IQ3_S block has a non-finite scale" + ); + assert!(iq3_s::decode_into(&block, &mut [0.0; iq3_s::BLOCK_ELEMENTS]).is_err()); + rejected += 1; + } + assert_eq!(rejected, 2_048); + } + #[test] fn q8_0_and_q2_0_match_known_block_values() { let mut q8 = [0u8; 34]; diff --git a/control-plane/src/kar_codec.rs b/control-plane/src/kar_codec.rs index bc047dd8..e5b8d34a 100644 --- a/control-plane/src/kar_codec.rs +++ b/control-plane/src/kar_codec.rs @@ -322,22 +322,7 @@ fn f64_to_f16_bits(value: f64) -> u16 { sign | ((half_exponent as u16) << 10) | ((rounded >> 42) as u16) } -pub fn f16_bits_to_f32(bits: u16) -> f32 { - let sign = (u32::from(bits & 0x8000)) << 16; - let exponent = (bits >> 10) & 0x1f; - let mantissa = u32::from(bits & 0x03ff); - let result = match exponent { - 0 if mantissa == 0 => sign, - 0 => { - let leading = mantissa.leading_zeros() - 21; - let normalized = mantissa << leading; - sign | ((113 - leading) << 23) | ((normalized & 0x03ff) << 13) - } - 31 => sign | 0x7f80_0000 | (mantissa << 13), - _ => sign | ((u32::from(exponent) + 112) << 23) | (mantissa << 13), - }; - f32::from_bits(result) -} +pub use leleka_quant_core::f16_bits_to_f32; #[cfg(test)] mod tests { diff --git a/control-plane/src/lib.rs b/control-plane/src/lib.rs index fc902384..ef8c6e48 100644 --- a/control-plane/src/lib.rs +++ b/control-plane/src/lib.rs @@ -14,8 +14,7 @@ pub use leleka_model_format::gguf; pub mod gguf_f32_stream; mod history_store; mod immutable_directory; -pub mod iq3_s; -mod iq3s_grid; +pub use leleka_quant_core::iq3_s; pub mod kar; pub mod kar_codec; pub mod kar_fixture; diff --git a/crates/quant-core/Cargo.toml b/crates/quant-core/Cargo.toml new file mode 100644 index 00000000..6699f01e --- /dev/null +++ b/crates/quant-core/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "leleka-quant-core" +version = "0.1.0" +description = "Pure Rust bounded IQ3_S CPU decoding and binary16 conversion" +edition.workspace = true +license = "Apache-2.0 AND MIT" +rust-version.workspace = true + +[dev-dependencies] +sha2 = "0.11" +hex = "0.4" + +[lints] +workspace = true diff --git a/crates/quant-core/LICENSE-GGML b/crates/quant-core/LICENSE-GGML new file mode 100644 index 00000000..e7dca554 --- /dev/null +++ b/crates/quant-core/LICENSE-GGML @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2023-2026 The ggml authors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/crates/quant-core/README.md b/crates/quant-core/README.md new file mode 100644 index 00000000..0fdf8eac --- /dev/null +++ b/crates/quant-core/README.md @@ -0,0 +1,46 @@ +# Leleka quantization foundation + +`leleka-quant-core` extracts the existing IQ3_S CPU decoder and binary16-to-binary32 +conversion into 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. +The control plane reexports `iq3_s` and `kar_codec::f16_bits_to_f32`, preserving +all existing preparation and KAR consumer paths. Its separate legacy GGML/build +dependencies remain; this extraction does not make the control plane autonomous. + +## Contract and provenance + +IQ3_S decoding accepts 110-byte blocks with 256 output elements. It retains the +existing layout, finite-scale rejection, checked output geometry, arithmetic, +pinned grid and golden hashes. `decode_into` processes blocks in order; if a later +block is invalid, earlier output blocks may already have been written. Callers +must handle the error and must not consume a partial result as successful output. +Binary16 conversion preserves the existing signed-zero, subnormal, infinity and +NaN payload bit behavior. Encoding and its rounding helpers remain in KAR. + +The grid was imported from `ggml-common.h` at upstream Strata commit +`d9ab8435f654c368c586340d490915f6addf56a3`. Its ggml MIT notice is copied unchanged +in [LICENSE-GGML](LICENSE-GGML); the table's source provenance remains in its +header. The Rust extraction retains the original decoder and helper arithmetic. +No engine file is included or read to build or use this crate. + +The existing tests preserve the SHA-256 of the little-endian grid bytes +(`bd1af4945a1717c65610b0284e4628b9a1ba3b306fae3a06f6e5f597356e349f`) +and the mixed-block decoded f32 bytes +(`cfee2753d1b389fe4ee30994ff3387d4400745b8432aeb32cb4d7fced39949ec`). +Independent IEEE 754 boundary encodings additionally check the shared conversion. + +## Standalone checks and limits + +```sh +cargo fmt --manifest-path crates/quant-core/Cargo.toml --check +cargo clippy --locked -p leleka-quant-core --all-targets -- -D warnings +cargo test --locked -p leleka-quant-core +cargo tree --locked -p leleka-quant-core --edges normal +``` + +These are bounded CPU preparation primitives and synthetic numerical checks. +They do not implement compute shaders, GPU dispatch, complete model loading, +inference, model quality or performance qualification. Independent C-oracle +checks in the control plane are separate offline tests; they do not add a native +dependency to this crate. diff --git a/control-plane/src/iq3_s.rs b/crates/quant-core/src/iq3_s.rs similarity index 98% rename from control-plane/src/iq3_s.rs rename to crates/quant-core/src/iq3_s.rs index aca002db..4b2e1bee 100644 --- a/control-plane/src/iq3_s.rs +++ b/crates/quant-core/src/iq3_s.rs @@ -2,7 +2,7 @@ //! Layout and grid are pinned to Strata upstream d9ab8435. This is preparation //! code, not a serving kernel; numerical parity with a real model is pending. -use crate::{iq3s_grid::IQ3S_GRID, kar_codec::f16_bits_to_f32}; +use crate::{f16_bits_to_f32, iq3s_grid::IQ3S_GRID}; pub const BLOCK_BYTES: usize = 110; pub const BLOCK_ELEMENTS: usize = 256; diff --git a/control-plane/src/iq3s_grid.rs b/crates/quant-core/src/iq3s_grid.rs similarity index 98% rename from control-plane/src/iq3s_grid.rs rename to crates/quant-core/src/iq3s_grid.rs index a7586b42..2c1bae69 100644 --- a/control-plane/src/iq3s_grid.rs +++ b/crates/quant-core/src/iq3s_grid.rs @@ -1,6 +1,6 @@ // iq3s_grid from ggml-common.h at Strata upstream d9ab8435f654c368c586340d490915f6addf56a3. // Copyright (c) 2023-2026 The ggml authors. MIT License. -// See engine/strata/third_party/ggml/LICENSE for the full license text. +// See LICENSE-GGML in this crate for the full license text. // This table is pinned to the imported upstream revision; do not regenerate silently. pub const IQ3S_GRID: [u32; 512] = [ diff --git a/crates/quant-core/src/lib.rs b/crates/quant-core/src/lib.rs new file mode 100644 index 00000000..7b616d30 --- /dev/null +++ b/crates/quant-core/src/lib.rs @@ -0,0 +1,48 @@ +//! Pure Rust CPU quantization primitives for Leleka preparation tools. +//! No inference, GPU operation or complete model support is implied. + +pub mod iq3_s; +mod iq3s_grid; + +pub fn f16_bits_to_f32(bits: u16) -> f32 { + let sign = (u32::from(bits & 0x8000)) << 16; + let exponent = (bits >> 10) & 0x1f; + let mantissa = u32::from(bits & 0x03ff); + let result = match exponent { + 0 if mantissa == 0 => sign, + 0 => { + let leading = mantissa.leading_zeros() - 21; + let normalized = mantissa << leading; + sign | ((113 - leading) << 23) | ((normalized & 0x03ff) << 13) + } + 31 => sign | 0x7f80_0000 | (mantissa << 13), + _ => sign | ((u32::from(exponent) + 112) << 23) | (mantissa << 13), + }; + f32::from_bits(result) +} + +#[cfg(test)] +mod tests { + use super::f16_bits_to_f32; + + #[test] + fn binary16_boundaries_preserve_exact_binary32_bits() { + // Independent IEEE 754 encodings, including signed zero and NaN payloads. + for (half, single) in [ + (0x0000, 0x0000_0000), + (0x8000, 0x8000_0000), + (0x0001, 0x3380_0000), + (0x03ff, 0x387f_c000), + (0x0400, 0x3880_0000), + (0x3c00, 0x3f80_0000), + (0xc000, 0xc000_0000), + (0x7bff, 0x477f_e000), + (0x7c00, 0x7f80_0000), + (0xfc00, 0xff80_0000), + (0x7c01, 0x7f80_2000), + (0xfe00, 0xffc0_0000), + ] { + assert_eq!(f16_bits_to_f32(half).to_bits(), single); + } + } +} diff --git a/docs/iq3-reference-parity.md b/docs/iq3-reference-parity.md new file mode 100644 index 00000000..d65204ef --- /dev/null +++ b/docs/iq3-reference-parity.md @@ -0,0 +1,63 @@ +# IQ3_S CPU reference parity + +The Rust IQ3_S decoder uses the 256-value / 110-byte block layout and grid pinned +to Strata `d9ab8435f654c368c586340d490915f6addf56a3`. Its offline C oracle is the +vendored GGML decoder from llama.cpp `3cf03257f219afbe7334045ff7c6a06ac68c627d`, +recorded in [GGML provenance](../control-plane/third_party/ggml/UPSTREAM.md). +The existing control-plane bridge statically compiles that pinned CPU code. The +independent Rust quantization crate does not depend on the C oracle or bridge. +No upstream source or pin is changed for these tests. + +The new bridge test exhausts all **63,488 finite FP16 scale encodings**: both +signed zeros, every positive/negative subnormal, every positive/negative normal, +and the maximum finite scale of either sign. Each gets a deterministic generated +110-byte block with varied packed fields. An explicit byte bijection at each +field position guarantees all 256 byte values over a complete low-pattern-byte +sweep; high-pattern-byte and position mixing vary the joint block patterns. Coverage assertions require every +8-bit low-index, high-index and sign value at every corresponding field position, +every scale nibble at every subblock, and all 512 combined grid indexes. + +Every one of the 256 decoded values is compared with `f32::to_bits()` against +the pinned C output: the tolerance is **zero**, including signed zero. This is +63,488 blocks / 16,252,928 element comparisons. It exhausts the FP16 scale domain +and observes each packed field value; it does not exhaust all possible joint +combinations of the 108 packed bytes. A separate 14-block contiguous batch +checks the same exact-bit contract through both `decode_into` paths with a +source pointer deliberately unaligned for the C bridge. + +The Rust decoder's existing error for a NaN or infinity block scale is retained. +All **2,048 nonfinite FP16 encodings** are tested for refusal by both Rust entry +points. They are outside the C numerical parity domain, and are never silently +skipped as successful parity cases. The existing pinned block-size, original mixed IQ3_S block and known +Q8_0/Q2_0 tests are retained. + +Fixtures are generated synthetic packed bytes, not model weights or captures. +These checks qualify CPU block decoding only. They do not establish real-model +parity, inference quality, readiness, GPU behavior or a performance improvement. +The eventual production engine must qualify its own load, arithmetic and model +semantics independently. + +## Targeted gate + +```sh +cargo test --locked -p strata-control --lib ggml_bridge::tests +``` + +## Actual local CPU result, 2026-10-07 + +- Rust: `rustc 1.99.0 (b940084d7 2026-09-28)`. +- Host target: `aarch64-apple-darwin` (Darwin arm64). +- C compiler: Apple Clang 21.0.0 (`clang-2100.1.1.101`). +- Command above: **6 passed, 0 failed** (172 unrelated tests filtered). +- Finite-scale element bits, every packed-field coverage assertion, unaligned + batch parity and all nonfinite-scale refusals passed. +- Vendored GGML manifest hashes were checked before the run. The production + bridge body and the three original bridge tests remain unchanged. + +The first draft generator passed every numerical comparison but failed its +sign-byte coverage assertion. The generator was corrected to the explicit byte +bijection described above; all exact-bit and coverage assertions were retained, +and the complete targeted gate was rerun successfully. No decoder arithmetic or +numerical tolerance was changed. Both private temporary build targets were +cleaned. This result applies to this CPU/compiler configuration; Linux/GCC, +real-model and GPU qualification remain separate. diff --git a/scripts/check-local.sh b/scripts/check-local.sh index 9d6f5675..b2130db3 100755 --- a/scripts/check-local.sh +++ b/scripts/check-local.sh @@ -21,6 +21,9 @@ cargo fmt --manifest-path "${repo_root}/crates/model-format/Cargo.toml" --check cargo clippy --manifest-path "${repo_root}/Cargo.toml" --locked -p leleka-model-format --all-targets -- -D warnings cargo test --manifest-path "${repo_root}/Cargo.toml" --locked -p leleka-model-format cargo test --manifest-path "${repo_root}/Cargo.toml" --locked -p leleka-backend-api +cargo fmt --manifest-path "${repo_root}/crates/quant-core/Cargo.toml" --check +cargo clippy --manifest-path "${repo_root}/Cargo.toml" --locked -p leleka-quant-core --all-targets -- -D warnings +cargo test --manifest-path "${repo_root}/Cargo.toml" --locked -p leleka-quant-core cargo fmt --manifest-path "${repo_root}/control-plane/Cargo.toml" --check cargo clippy --manifest-path "${repo_root}/control-plane/Cargo.toml" --locked --all-targets -- -D warnings cargo test --manifest-path "${repo_root}/control-plane/Cargo.toml" --locked -- 2.54.0