From 2f182575dce4701fbcbd1a8bc4f4af117c38a2b9 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Fri, 2 Oct 2026 21:31:48 +0200 Subject: [PATCH] Extract shared KAR preview tensor encoder --- control-plane/src/prepare_preview.rs | 143 ++++++++++++++++----------- docs/build-validation.md | 1 + 2 files changed, 84 insertions(+), 60 deletions(-) diff --git a/control-plane/src/prepare_preview.rs b/control-plane/src/prepare_preview.rs index 4dee6fdb..84045aa0 100644 --- a/control-plane/src/prepare_preview.rs +++ b/control-plane/src/prepare_preview.rs @@ -268,68 +268,18 @@ fn prepare( (weights, digest, absolute) }; drop(raw); - let normalized = kar_codec::normalize_for_calibration(&weights, 32)?; - let calibration = kar_codec::fit_topdown(&normalized.values, levels)?; - let encoded = - kar_codec::encode_with_boundaries(&weights, 32, &calibration.boundaries, levels)?; - let plane_refs = encoded.planes.iter().map(Vec::as_slice).collect::>(); - let mut decoded = vec![0.0f32; weights.len()]; - kar_codec::decode_range( - &encoded.scales, - &calibration.books[usize::from(levels) - 1], - &plane_refs, - 32, - 0, - &mut decoded, - )?; - let (error_sum, reference_sum) = weights.iter().zip(&decoded).fold( - (0.0f64, 0.0f64), - |(error_sum, reference_sum), (original, rebuilt)| { - let delta = f64::from(*original) - f64::from(*rebuilt); - ( - error_sum + delta * delta, - reference_sum + f64::from(*original).powi(2), - ) - }, - ); - let relative_l2 = if reference_sum == 0.0 { - error_sum.sqrt() - } else { - (error_sum / reference_sum).sqrt() - }; - maximum_relative_l2 = maximum_relative_l2.max(relative_l2); - let books = calibration - .books - .iter() - .map(Vec::as_slice) - .collect::>(); - let coded_tensor = kar_writer::Tensor { - name: &tensor.name, - dims: &tensor.dimensions, - source_dtype: 0, - source_digest: tensor_digest, - source_offset, - data: kar_writer::TensorData::Nested { - group: 32, - nesting: 0, - planes_min: 1, - planes_max: levels, - scales: &encoded.scales, - books: &books, - planes: &plane_refs, - }, - }; let section_path = staging.0.join(format!("{number:06}.section")); - let section = kar_writer::write_nested_section(§ion_path, &coded_tensor)?; - prepared.push(PreparedTensor { - name: tensor.name.clone(), - dims: tensor.dimensions.clone(), - source_digest: tensor_digest, + let (coded, relative_l2) = encode_preview_tensor( + &tensor.name, + &tensor.dimensions, + &weights, + tensor_digest, source_offset, - section_path, - section_bytes: section.bytes, - section_digest: section.digest, - }); + §ion_path, + levels, + )?; + maximum_relative_l2 = maximum_relative_l2.max(relative_l2); + prepared.push(coded); } if source_file .metadata() @@ -402,6 +352,79 @@ fn prepare( }) } +fn encode_preview_tensor( + name: &str, + dimensions: &[u64], + weights: &[f32], + source_digest: [u8; 32], + source_offset: u64, + section_path: &Path, + levels: u8, +) -> Result<(PreparedTensor, f64), String> { + let normalized = kar_codec::normalize_for_calibration(weights, 32)?; + let calibration = kar_codec::fit_topdown(&normalized.values, levels)?; + let encoded = kar_codec::encode_with_boundaries(weights, 32, &calibration.boundaries, levels)?; + let plane_refs = encoded.planes.iter().map(Vec::as_slice).collect::>(); + let mut decoded = vec![0.0f32; weights.len()]; + kar_codec::decode_range( + &encoded.scales, + &calibration.books[usize::from(levels) - 1], + &plane_refs, + 32, + 0, + &mut decoded, + )?; + let (error_sum, reference_sum) = weights.iter().zip(&decoded).fold( + (0.0f64, 0.0f64), + |(error_sum, reference_sum), (original, rebuilt)| { + let delta = f64::from(*original) - f64::from(*rebuilt); + ( + error_sum + delta * delta, + reference_sum + f64::from(*original).powi(2), + ) + }, + ); + let relative_l2 = if reference_sum == 0.0 { + error_sum.sqrt() + } else { + (error_sum / reference_sum).sqrt() + }; + let books = calibration + .books + .iter() + .map(Vec::as_slice) + .collect::>(); + let coded_tensor = kar_writer::Tensor { + name, + dims: dimensions, + source_dtype: 0, + source_digest, + source_offset, + data: kar_writer::TensorData::Nested { + group: 32, + nesting: 0, + planes_min: 1, + planes_max: levels, + scales: &encoded.scales, + books: &books, + planes: &plane_refs, + }, + }; + let section = kar_writer::write_nested_section(section_path, &coded_tensor)?; + Ok(( + PreparedTensor { + name: name.to_owned(), + dims: dimensions.to_vec(), + source_digest, + source_offset, + section_path: section_path.to_path_buf(), + section_bytes: section.bytes, + section_digest: section.digest, + }, + relative_l2, + )) +} + pub fn verify_iq3(source_path: &Path, archive_path: &Path) -> Result { verify_derived(source_path, archive_path, PreviewKind::Iq3) } diff --git a/docs/build-validation.md b/docs/build-validation.md index 4265c7c0..df06b1cb 100644 --- a/docs/build-validation.md +++ b/docs/build-validation.md @@ -94,3 +94,4 @@ The test toolchain was installed into ignored `artifacts/tool-venv/` for this ru - Added `model derive-mixed-identity` for one GGUF containing IQ3_S and F32/F16/BF16 tensors. A four-tensor fixture with directory order different from physical order matched the independently assembled F32 byte-stream SHA-256, including half and bfloat conversions, and the all-IQ3-only derivation rejected it. The command uses a fixed 28,160-byte source buffer and writes no expanded file. All 44 Rust tests, Clippy with warnings denied, and Linux/arm64 musl cross-check pass. Mixed KAR preparation, real-model parity, and GPU quality remain open. - Added `model prepare-mixed-preview` and `model verify-mixed-preview`, with a separate versioned sidecar carrying each original tensor kind and digest. A four-type synthetic GGUF passed preparation and verification in Rust tests. A separate two-type CLI smoke produced a KAR archive whose virtual F32 SHA-256 was `c407838a4718093d8f2699209c7cac8b998a47b937e5afe59e4c5a0af09033a7`; the verifier matched the source, sidecar, KAR source records, and payload CRCs. All 45 Rust tests, Clippy with warnings denied, and Linux/arm64 musl cross-check pass. The preview remains capped at 64 MiB input and is not approved for serving. - Added `model derive-sharded-identity` for manifest-pinned GGUF shards. A two-file fixture deliberately listed IQ3_S before F32 in its manifest; native derivation sorted filenames, checked both size/SHA-256 values, and assigned global F32 offsets 0 and 128. Replacing a manifest SHA-256 with the wrong value was rejected. A separate CLI smoke emitted the expected derived stream SHA-256 `e529f5e2f7aac1aa5509fabe728d84ab876c64754635963825e265cd70cb8b05`. All 46 Rust tests, Clippy with warnings denied, and Linux/arm64 musl cross-check pass. No sharded KAR archive or real-model conversion was attempted. +- Extracted the shared one-tensor preview encoder and reconstruction check for future sharded preparation. Existing F32, IQ3_S, and mixed preview tests passed. Rebuilt the CLI and reran the pinned two-type mixed fixture: the derived F32 SHA-256 remained `c407838a4718093d8f2699209c7cac8b998a47b937e5afe59e4c5a0af09033a7` and the full KAR archive SHA-256 remained `4053e787d46b2cf2bca3d67e38d06e1ee96a157e80e3155c8dbdbf36835df88c` byte for byte. This is a non-lossy refactor of the preview implementation, not a quality result for the lossy format.