Stream raw tensor input into KAR archives

This commit is contained in:
Pavlo Ratushnyi
2026-10-02 20:18:34 +02:00
parent 9c5ad4019b
commit 9e4d38d8ae
4 changed files with 148 additions and 3 deletions
+145 -2
View File
@@ -4,7 +4,7 @@
use std::{
collections::HashSet,
fs::{self, File, OpenOptions},
io::{Seek, SeekFrom, Write},
io::{Read, Seek, SeekFrom, Write},
path::Path,
};
@@ -32,6 +32,11 @@ pub struct Tensor<'a> {
pub enum TensorData<'a> {
Raw(&'a [u8]),
RawFile {
path: &'a Path,
offset: u64,
bytes: u64,
},
Nested {
group: u16,
nesting: u8,
@@ -121,6 +126,20 @@ pub fn write_archive(
}
(n_elements, round_up(raw.len() as u64, 256)?, 0, 0, 0, 0)
}
TensorData::RawFile { bytes, .. } => {
let width = if tensor.source_dtype == 0 { 4 } else { 2 };
if *bytes
!= n_elements
.checked_mul(width)
.ok_or("KAR RAW byte count overflow")?
{
return Err(format!(
"{}: RAW file byte count differs from tensor shape",
tensor.name
));
}
(n_elements, round_up(*bytes, 256)?, 0, 0, 0, 0)
}
TensorData::Nested {
group,
nesting,
@@ -371,6 +390,38 @@ fn write_section(file: &mut File, entry: &Placed<'_>) -> Result<u32, String> {
let mut written = 0u64;
match &entry.tensor.data {
TensorData::Raw(raw) => write_bytes(file, raw, &mut crc, &mut written)?,
TensorData::RawFile {
path,
offset,
bytes,
} => {
let mut source = File::open(path).map_err(|error| error.to_string())?;
let source_len = source.metadata().map_err(|error| error.to_string())?.len();
if offset
.checked_add(*bytes)
.is_none_or(|end| end > source_len)
{
return Err("KAR RAW source file is truncated".into());
}
source
.seek(SeekFrom::Start(*offset))
.map_err(|error| error.to_string())?;
let mut remaining = *bytes;
let mut buffer = vec![0u8; 1024 * 1024];
let mut digest = Sha256::new();
while remaining > 0 {
let count = remaining.min(buffer.len() as u64) as usize;
source
.read_exact(&mut buffer[..count])
.map_err(|error| error.to_string())?;
digest.update(&buffer[..count]);
write_bytes(file, &buffer[..count], &mut crc, &mut written)?;
remaining -= count as u64;
}
if digest.finalize().as_slice() != entry.tensor.source_digest {
return Err(format!("{}: RAW source digest mismatch", entry.tensor.name));
}
}
TensorData::Nested {
scales,
books,
@@ -450,7 +501,10 @@ fn write_record(record: &mut [u8], entry: &Placed<'_>) -> Result<(), String> {
u16::try_from(tensor.name.len()).map_err(|_| "KAR tensor name too long")?,
);
record[6] = tensor.dims.len() as u8;
record[7] = u8::from(matches!(tensor.data, TensorData::Raw(_)));
record[7] = u8::from(matches!(
tensor.data,
TensorData::Raw(_) | TensorData::RawFile { .. }
));
for index in 0..4 {
put_u64(
record,
@@ -510,6 +564,43 @@ fn put_u64(bytes: &mut [u8], offset: usize, value: u64) {
mod tests {
use super::*;
#[test]
fn streams_raw_tensor_across_buffer_boundary() {
let raw = vec![0x5au8; 1_048_580];
let source = SourceIdentity {
name: "large-synthetic",
architecture: "qwen35",
builder: "strata-next-test",
digest: Sha256::digest(&raw).into(),
total_elements: 262_145,
bytes: raw.len() as u64,
};
let input =
std::env::temp_dir().join(format!("strata-kar-large-{}.bin", std::process::id()));
let output =
std::env::temp_dir().join(format!("strata-kar-large-{}.kar", std::process::id()));
let _ = fs::remove_file(&output);
fs::write(&input, &raw).unwrap();
let tensors = [Tensor {
name: "large",
dims: &[262_145],
source_dtype: 0,
source_digest: Sha256::digest(&raw).into(),
source_offset: 0,
data: TensorData::RawFile {
path: &input,
offset: 0,
bytes: raw.len() as u64,
},
}];
let summary = write_archive(&output, &source, &tensors).unwrap();
assert_eq!(summary.tensor_count, 1);
assert_eq!(summary.total_elements, 262_145);
assert_eq!(kar::verify(&output).unwrap(), summary);
fs::remove_file(output).unwrap();
fs::remove_file(input).unwrap();
}
#[test]
fn archive_bytes_match_pinned_koference_reference_writer() {
// Oracle: koference 806d2398, r08/code/kar_container.py, RAW + NESTED fixture.
@@ -602,6 +693,58 @@ mod tests {
.contains("non-finite f16 scale")
);
assert!(!other.exists());
let raw_file =
path.with_file_name(format!("strata-kar-raw-input-{}.bin", std::process::id()));
let mut padded_raw = vec![0u8; 17];
padded_raw.extend_from_slice(&raw);
fs::write(&raw_file, &padded_raw).unwrap();
let streamed_tensors = [
Tensor {
name: "norm",
dims: &[32],
source_dtype: 0,
source_digest: Sha256::digest(&raw).into(),
source_offset: 0,
data: TensorData::RawFile {
path: &raw_file,
offset: 17,
bytes: raw.len() as u64,
},
},
Tensor {
name: "expert",
dims: &[32],
source_dtype: 1,
source_digest: Sha256::digest(b"weights").into(),
source_offset: 0,
data: TensorData::Nested {
group: 32,
nesting: 0,
planes_min: 1,
planes_max: 2,
scales: &[0x3c00],
books: &books,
planes: &planes,
},
},
];
let streamed =
path.with_file_name(format!("strata-kar-streamed-{}.kar", std::process::id()));
let _ = fs::remove_file(&streamed);
write_archive(&streamed, &source, &streamed_tensors).unwrap();
assert_eq!(fs::read(&streamed).unwrap(), archive);
padded_raw[17] ^= 1;
fs::write(&raw_file, padded_raw).unwrap();
let corrupt = path.with_file_name(format!("strata-kar-corrupt-{}.kar", std::process::id()));
let _ = fs::remove_file(&corrupt);
assert!(
write_archive(&corrupt, &source, &streamed_tensors)
.unwrap_err()
.contains("RAW source digest mismatch")
);
assert!(!corrupt.exists());
fs::remove_file(streamed).unwrap();
fs::remove_file(raw_file).unwrap();
fs::remove_file(path).unwrap();
}
}
+1
View File
@@ -80,3 +80,4 @@ The test toolchain was installed into ignored `artifacts/tool-venv/` for this ru
- Rust 1.99 formatting, Clippy with warnings denied, and all 32 Rust tests pass with the native writer.
- Added a GGUF tensor index that checks exact source block lengths and can hash one tensor with a fixed 1 MiB buffer. A synthetic mixed F32/IQ3_S fixture verifies offsets, lengths, and rejection of overlapping sections, a misaligned quantized row, and an unsupported type. All 33 Rust tests and Clippy with warnings denied pass; this is a source-layout check, not a KAR encoder or model conversion.
- The `model index /tmp/strata-next-index-smoke.gguf --hash` CLI emitted the expected two JSON records: F32 at absolute offset 128 with 16 bytes, and IQ3_S at 160 with 110 bytes; both SHA-256 values matched the synthetic zero payloads. `cargo check --locked --target aarch64-unknown-linux-musl` passed with this source.
- The KAR writer's file-backed RAW path generated the same complete archive bytes as its in-memory path, rejected a changed source digest without publishing a destination, and passed a separate 1,048,580-byte input crossing the 1 MiB copy boundary. Rust 1.99 formatting, Clippy with warnings denied, all 34 tests, and Linux/arm64 musl cross-check pass. NESTED encoded data is still in-memory, so full-model conversion is not bounded yet.
+1 -1
View File
@@ -12,7 +12,7 @@ The current `model inspect-kar` command performs bounded structural checks, head
The Rust `kar_writer` module now emits a KAR-2 container from already coded RAW/NESTED tensor slices. A synthetic two-tensor output matches the pinned koference reference writer byte for byte, including header, directory, aligned payload, CRCs, and digest. The writer verifies its temporary file before atomic no-replace publication and rejects non-finite f16 scales/books. It is an internal building block: it does not encode GGUF weights, choose compression levels, or stream a whole model tensor by tensor yet.
`strata-next model index FILE.gguf [--hash]` prints one JSON record per tensor with checked absolute offset, exact source byte count, type, and dimensions. `--hash` adds a SHA-256 computed with a fixed 1 MiB buffer. The index uses Strata's pinned GGUF block geometry, including IQ3_S, and rejects unknown types, overlapping spans, truncated payloads, and rows that do not align to quantization blocks. This is input preparation for a streamed converter; it does not decode or re-encode the tensor.
`strata-next model index FILE.gguf [--hash]` prints one JSON record per tensor with checked absolute offset, exact source byte count, type, and dimensions. `--hash` adds a SHA-256 computed with a fixed 1 MiB buffer. The index uses Strata's pinned GGUF block geometry, including IQ3_S, and rejects unknown types, overlapping spans, truncated payloads, and rows that do not align to quantization blocks. The KAR writer can now stream a RAW tensor from a file through a 1 MiB buffer and check its source digest before publication. This is input preparation for a streamed converter; quantized tensors still need a native encoder.
## GPU path
+1
View File
@@ -56,6 +56,7 @@ The target interface is one Linux command, `strata-next`, with `serve`, `model f
- [x] Add bounded native KAR-2 metadata inspection, streaming payload CRC verification, and optional source-manifest identity check (decode still pending).
- [x] Emit a byte-identical synthetic KAR-2 RAW/NESTED archive from native Rust tensor slices; publish after verification without overwriting an existing file.
- [x] Index supported GGUF tensor payloads with exact block geometry and bounded per-tensor hashing; reject overlapping, truncated, or malformed source layouts.
- [x] Stream RAW tensor bytes into KAR-2 with a fixed 1 MiB buffer and per-tensor digest verification.
- [ ] Feed the native writer from a bounded-memory GGUF tensor iterator and a native KAR encoder; implement `model prepare` on real shards.
- [ ] Make one-command `serve` fetch, verify, and prepare missing model assets, then reuse the verified compressed archive.
- [ ] Compare KAR reconstruction with its CPU oracle; run full-model quality before making the compressed path a default.