Desktop foundation / core (ubuntu-latest) (push) Failing after 28s
Desktop foundation / core (macos-latest) (push) Canceled after 0s
Desktop foundation / core (windows-latest) (push) Canceled after 0s
Linux / verify (push) Canceled after 0s
Linux / keyless-cuda (push) Canceled after 0s
Linux / static-cuda-package (push) Canceled after 0s
Linux / hosted-cuda-package (push) Canceled after 0s
Linux / linux-static-cli (push) Canceled after 0s
Linux / linux-cli-container (push) Canceled after 0s
Linux / release-cli (push) Canceled after 0s
1294 lines
44 KiB
Rust
1294 lines
44 KiB
Rust
//! KAR-2 container writer for already encoded tensors. Compression policy and
|
|
//! GGUF conversion are separate; this module never chooses a lossy precision.
|
|
|
|
use std::{
|
|
collections::HashSet,
|
|
fs::{self, File, OpenOptions},
|
|
io::{Read, Seek, SeekFrom, Write},
|
|
path::Path,
|
|
};
|
|
|
|
use sha2::{Digest, Sha256};
|
|
|
|
use crate::kar;
|
|
|
|
pub struct SourceIdentity<'a> {
|
|
pub name: &'a str,
|
|
pub architecture: &'a str,
|
|
pub builder: &'a str,
|
|
pub digest: [u8; 32],
|
|
pub total_elements: u64,
|
|
pub bytes: u64,
|
|
}
|
|
|
|
pub struct Tensor<'a> {
|
|
pub name: &'a str,
|
|
pub dims: &'a [u64],
|
|
pub source_dtype: u8,
|
|
pub source_digest: [u8; 32],
|
|
pub source_offset: u64,
|
|
pub data: TensorData<'a>,
|
|
}
|
|
|
|
pub enum TensorData<'a> {
|
|
Raw(&'a [u8]),
|
|
RawFile {
|
|
path: &'a Path,
|
|
offset: u64,
|
|
bytes: u64,
|
|
},
|
|
Nested {
|
|
group: u16,
|
|
nesting: u8,
|
|
planes_min: u8,
|
|
planes_max: u8,
|
|
scales: &'a [u16],
|
|
books: &'a [&'a [u16]],
|
|
planes: &'a [&'a [u32]],
|
|
},
|
|
/// Canonical KAR-2 section bytes produced by a tensor encoder. The writer
|
|
/// checks layout, f16 values, zero padding, and the supplied section hash.
|
|
NestedFile {
|
|
group: u16,
|
|
nesting: u8,
|
|
planes_min: u8,
|
|
planes_max: u8,
|
|
levels: u8,
|
|
path: &'a Path,
|
|
offset: u64,
|
|
bytes: u64,
|
|
digest: [u8; 32],
|
|
},
|
|
}
|
|
|
|
struct NestedLayout {
|
|
n_padded: u64,
|
|
section_bytes: u64,
|
|
scales_offset: u64,
|
|
books_offset: u64,
|
|
planes_offset: u64,
|
|
plane_stride: u32,
|
|
payload_bits: u64,
|
|
}
|
|
|
|
struct Placed<'a> {
|
|
tensor: &'a Tensor<'a>,
|
|
name_offset: u32,
|
|
n_elements: u64,
|
|
n_padded: u64,
|
|
section_offset: u64,
|
|
section_bytes: u64,
|
|
scales_offset: u64,
|
|
books_offset: u64,
|
|
planes_offset: u64,
|
|
plane_stride: u32,
|
|
payload_crc32: u32,
|
|
}
|
|
|
|
pub fn write_archive(
|
|
destination: &Path,
|
|
source: &SourceIdentity<'_>,
|
|
tensors: &[Tensor<'_>],
|
|
) -> Result<kar::Summary, String> {
|
|
write_archive_inner(destination, source, tensors, false)
|
|
}
|
|
|
|
/// Consume caller-owned, private staging files as their sections are copied.
|
|
/// This bounds peak disk use during streamed model preparation. A failed build
|
|
/// must be restarted because some input sections may already be removed.
|
|
pub(crate) fn write_archive_consuming_files(
|
|
destination: &Path,
|
|
source: &SourceIdentity<'_>,
|
|
tensors: &[Tensor<'_>],
|
|
) -> Result<kar::Summary, String> {
|
|
if tensors.iter().any(|tensor| {
|
|
!matches!(
|
|
&tensor.data,
|
|
TensorData::RawFile { .. } | TensorData::NestedFile { .. }
|
|
)
|
|
}) {
|
|
return Err("consuming KAR writer requires file-backed tensors".into());
|
|
}
|
|
write_archive_inner(destination, source, tensors, true)
|
|
}
|
|
|
|
fn write_archive_inner(
|
|
destination: &Path,
|
|
source: &SourceIdentity<'_>,
|
|
tensors: &[Tensor<'_>],
|
|
consume_files: bool,
|
|
) -> Result<kar::Summary, String> {
|
|
if fs::symlink_metadata(destination).is_ok() || tensors.is_empty() || tensors.len() > 100_000 {
|
|
return Err("KAR destination exists or tensor count is invalid".into());
|
|
}
|
|
if source.bytes == 0 || source.total_elements == 0 {
|
|
return Err("KAR source identity needs nonzero bytes and elements".into());
|
|
}
|
|
let mut names = Vec::new();
|
|
let mut name_offsets = Vec::with_capacity(tensors.len());
|
|
let mut unique = HashSet::new();
|
|
for tensor in tensors {
|
|
if tensor.name.is_empty() || !unique.insert(tensor.name) {
|
|
return Err("KAR tensor names must be nonempty and unique".into());
|
|
}
|
|
name_offsets.push(u32::try_from(names.len()).map_err(|_| "KAR string table is too large")?);
|
|
push_cstr(&mut names, tensor.name)?;
|
|
}
|
|
let source_name = u32::try_from(names.len()).map_err(|_| "KAR string table is too large")?;
|
|
push_cstr(&mut names, source.name)?;
|
|
let source_arch = u32::try_from(names.len()).map_err(|_| "KAR string table is too large")?;
|
|
push_cstr(&mut names, source.architecture)?;
|
|
let builder_name = u32::try_from(names.len()).map_err(|_| "KAR string table is too large")?;
|
|
push_cstr(&mut names, source.builder)?;
|
|
if names.len() > 64 * 1024 * 1024 {
|
|
return Err("KAR string table exceeds inspector limit".into());
|
|
}
|
|
|
|
let directory_offset = 256u64;
|
|
let directory_bytes = (tensors.len() as u64)
|
|
.checked_mul(192)
|
|
.ok_or("KAR directory overflow")?;
|
|
let string_offset = round_up(directory_offset + directory_bytes, 64)?;
|
|
let payload_offset = round_up(string_offset + names.len() as u64, 256)?;
|
|
let mut cursor = payload_offset;
|
|
let mut total_elements = 0u64;
|
|
let mut payload_bits = 0u64;
|
|
let mut min_planes = u8::MAX;
|
|
let mut max_planes = 0u8;
|
|
let mut placed = Vec::with_capacity(tensors.len());
|
|
for (tensor, &name_offset) in tensors.iter().zip(&name_offsets) {
|
|
let n_elements = validate_shape(tensor)?;
|
|
total_elements = total_elements
|
|
.checked_add(n_elements)
|
|
.ok_or("KAR element count overflow")?;
|
|
let (n_padded, section_bytes, scales_offset, books_offset, planes_offset, plane_stride) =
|
|
match &tensor.data {
|
|
TensorData::Raw(raw) => {
|
|
let width = if tensor.source_dtype == 0 { 4 } else { 2 };
|
|
if raw.len() as u64
|
|
!= n_elements
|
|
.checked_mul(width)
|
|
.ok_or("KAR RAW byte count overflow")?
|
|
{
|
|
return Err(format!(
|
|
"{}: RAW byte count differs from tensor shape",
|
|
tensor.name
|
|
));
|
|
}
|
|
(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,
|
|
planes_min,
|
|
planes_max,
|
|
scales,
|
|
books,
|
|
planes,
|
|
} => {
|
|
let levels = u8::try_from(planes.len()).map_err(|_| "too many KAR planes")?;
|
|
let layout = nested_layout(
|
|
cursor,
|
|
n_elements,
|
|
*group,
|
|
*nesting,
|
|
*planes_min,
|
|
*planes_max,
|
|
levels,
|
|
)?;
|
|
validate_nested_slices(tensor.name, &layout, *group, scales, books, planes)?;
|
|
payload_bits = payload_bits
|
|
.checked_add(layout.payload_bits)
|
|
.ok_or("KAR payload bit count overflow")?;
|
|
min_planes = min_planes.min(*planes_min);
|
|
max_planes = max_planes.max(*planes_max);
|
|
(
|
|
layout.n_padded,
|
|
layout.section_bytes,
|
|
layout.scales_offset,
|
|
layout.books_offset,
|
|
layout.planes_offset,
|
|
layout.plane_stride,
|
|
)
|
|
}
|
|
TensorData::NestedFile {
|
|
group,
|
|
nesting,
|
|
planes_min,
|
|
planes_max,
|
|
levels,
|
|
bytes,
|
|
..
|
|
} => {
|
|
let layout = nested_layout(
|
|
cursor,
|
|
n_elements,
|
|
*group,
|
|
*nesting,
|
|
*planes_min,
|
|
*planes_max,
|
|
*levels,
|
|
)?;
|
|
if *bytes != layout.section_bytes {
|
|
return Err(format!(
|
|
"{}: nested file section size mismatch",
|
|
tensor.name
|
|
));
|
|
}
|
|
payload_bits = payload_bits
|
|
.checked_add(layout.payload_bits)
|
|
.ok_or("KAR payload bit count overflow")?;
|
|
min_planes = min_planes.min(*planes_min);
|
|
max_planes = max_planes.max(*planes_max);
|
|
(
|
|
layout.n_padded,
|
|
layout.section_bytes,
|
|
layout.scales_offset,
|
|
layout.books_offset,
|
|
layout.planes_offset,
|
|
layout.plane_stride,
|
|
)
|
|
}
|
|
};
|
|
placed.push(Placed {
|
|
tensor,
|
|
name_offset,
|
|
n_elements,
|
|
n_padded,
|
|
section_offset: cursor,
|
|
section_bytes,
|
|
scales_offset,
|
|
books_offset,
|
|
planes_offset,
|
|
plane_stride,
|
|
payload_crc32: 0,
|
|
});
|
|
cursor = cursor
|
|
.checked_add(section_bytes)
|
|
.ok_or("KAR archive size overflow")?;
|
|
}
|
|
if total_elements > source.total_elements {
|
|
return Err("KAR tensors exceed source element count".into());
|
|
}
|
|
let archive_bytes = cursor;
|
|
let temporary = destination.with_file_name(format!(
|
|
"{}.part",
|
|
destination
|
|
.file_name()
|
|
.ok_or("KAR destination has no filename")?
|
|
.to_string_lossy()
|
|
));
|
|
let mut file = OpenOptions::new()
|
|
.write(true)
|
|
.create_new(true)
|
|
.open(&temporary)
|
|
.map_err(|error| error.to_string())?;
|
|
let result = (|| -> Result<(), String> {
|
|
file.set_len(payload_offset)
|
|
.map_err(|error| error.to_string())?;
|
|
file.seek(SeekFrom::Start(string_offset))
|
|
.map_err(|error| error.to_string())?;
|
|
file.write_all(&names).map_err(|error| error.to_string())?;
|
|
for entry in &mut placed {
|
|
entry.payload_crc32 = write_section(&mut file, entry)?;
|
|
if consume_files {
|
|
let path = match &entry.tensor.data {
|
|
TensorData::RawFile { path, .. } | TensorData::NestedFile { path, .. } => path,
|
|
_ => unreachable!(),
|
|
};
|
|
fs::remove_file(path).map_err(|error| error.to_string())?;
|
|
}
|
|
}
|
|
if file.metadata().map_err(|error| error.to_string())?.len() != archive_bytes {
|
|
return Err("KAR writer produced the wrong archive length".into());
|
|
}
|
|
let mut directory = vec![0u8; directory_bytes as usize];
|
|
let (records, remainder) = directory.as_chunks_mut::<192>();
|
|
debug_assert!(remainder.is_empty());
|
|
for (entry, record) in placed.iter().zip(records) {
|
|
write_record(record, entry)?;
|
|
}
|
|
file.seek(SeekFrom::Start(directory_offset))
|
|
.map_err(|error| error.to_string())?;
|
|
file.write_all(&directory)
|
|
.map_err(|error| error.to_string())?;
|
|
let mut digest = Sha256::new();
|
|
digest.update(&names);
|
|
digest.update(&directory);
|
|
let mut header = [0u8; 256];
|
|
header[..8].copy_from_slice(b"KARCHIV2");
|
|
put_u32(&mut header, 8, 2);
|
|
put_u32(&mut header, 12, 0x0403_0201);
|
|
put_u32(&mut header, 16, 256);
|
|
put_u32(&mut header, 20, 192);
|
|
put_u64(&mut header, 24, directory_offset);
|
|
put_u32(&mut header, 32, tensors.len() as u32);
|
|
put_u64(&mut header, 40, string_offset);
|
|
put_u64(&mut header, 48, names.len() as u64);
|
|
put_u64(&mut header, 56, payload_offset);
|
|
put_u64(&mut header, 64, archive_bytes);
|
|
put_u64(&mut header, 72, total_elements);
|
|
put_u64(&mut header, 80, payload_bits);
|
|
put_u64(&mut header, 88, source.total_elements);
|
|
header[96..104]
|
|
.copy_from_slice(&(archive_bytes as f64 * 8.0 / total_elements as f64).to_le_bytes());
|
|
header[104] = if min_planes == u8::MAX { 0 } else { min_planes };
|
|
header[105] = max_planes;
|
|
header[106] = 1;
|
|
put_u32(&mut header, 108, source_name);
|
|
put_u32(&mut header, 112, source_arch);
|
|
put_u32(&mut header, 116, builder_name);
|
|
put_u64(&mut header, 120, source.bytes);
|
|
header[128..160].copy_from_slice(&source.digest);
|
|
header[160..192].copy_from_slice(&digest.finalize());
|
|
let header_crc = kar::crc32(&header[..192]);
|
|
put_u32(&mut header, 192, header_crc);
|
|
file.seek(SeekFrom::Start(0))
|
|
.map_err(|error| error.to_string())?;
|
|
file.write_all(&header).map_err(|error| error.to_string())?;
|
|
file.sync_all().map_err(|error| error.to_string())?;
|
|
Ok(())
|
|
})();
|
|
drop(file);
|
|
if let Err(error) = result {
|
|
let _ = fs::remove_file(&temporary);
|
|
return Err(error);
|
|
}
|
|
let summary = match kar::verify(&temporary) {
|
|
Ok(summary) => summary,
|
|
Err(error) => {
|
|
let _ = fs::remove_file(&temporary);
|
|
return Err(error);
|
|
}
|
|
};
|
|
// A hard link publishes a fully written archive atomically without replacing
|
|
// an existing destination, even if another writer won the race after preflight.
|
|
if let Err(error) = fs::hard_link(&temporary, destination) {
|
|
let _ = fs::remove_file(&temporary);
|
|
return Err(error.to_string());
|
|
}
|
|
fs::remove_file(&temporary).map_err(|error| error.to_string())?;
|
|
Ok(summary)
|
|
}
|
|
|
|
pub struct SectionSummary {
|
|
pub bytes: u64,
|
|
pub digest: [u8; 32],
|
|
}
|
|
|
|
/// Write one canonical NESTED section for later bounded-memory archive assembly.
|
|
/// The destination must not exist and is meant to live in a private staging dir.
|
|
pub fn write_nested_section(
|
|
destination: &Path,
|
|
tensor: &Tensor<'_>,
|
|
) -> Result<SectionSummary, String> {
|
|
let n_elements = validate_shape(tensor)?;
|
|
let TensorData::Nested {
|
|
group,
|
|
nesting,
|
|
planes_min,
|
|
planes_max,
|
|
scales,
|
|
books,
|
|
planes,
|
|
} = &tensor.data
|
|
else {
|
|
return Err("KAR section spool requires in-memory NESTED tensor".into());
|
|
};
|
|
let levels = u8::try_from(planes.len()).map_err(|_| "too many KAR planes")?;
|
|
let layout = nested_layout(
|
|
0,
|
|
n_elements,
|
|
*group,
|
|
*nesting,
|
|
*planes_min,
|
|
*planes_max,
|
|
levels,
|
|
)?;
|
|
validate_nested_slices(tensor.name, &layout, *group, scales, books, planes)?;
|
|
let entry = Placed {
|
|
tensor,
|
|
name_offset: 0,
|
|
n_elements,
|
|
n_padded: layout.n_padded,
|
|
section_offset: 0,
|
|
section_bytes: layout.section_bytes,
|
|
scales_offset: layout.scales_offset,
|
|
books_offset: layout.books_offset,
|
|
planes_offset: layout.planes_offset,
|
|
plane_stride: layout.plane_stride,
|
|
payload_crc32: 0,
|
|
};
|
|
let mut output = OpenOptions::new()
|
|
.write(true)
|
|
.create_new(true)
|
|
.open(destination)
|
|
.map_err(|error| error.to_string())?;
|
|
let result = (|| -> Result<(), String> {
|
|
write_section(&mut output, &entry)?;
|
|
if output.metadata().map_err(|error| error.to_string())?.len() != layout.section_bytes {
|
|
return Err("KAR section spool size mismatch".into());
|
|
}
|
|
output.sync_all().map_err(|error| error.to_string())?;
|
|
Ok(())
|
|
})();
|
|
drop(output);
|
|
if let Err(error) = result {
|
|
let _ = fs::remove_file(destination);
|
|
return Err(error);
|
|
}
|
|
let verified = (|| -> Result<SectionSummary, String> {
|
|
let mut file = File::open(destination).map_err(|error| error.to_string())?;
|
|
validate_nested_file(&mut file, &entry, 0, *group, levels)?;
|
|
file.seek(SeekFrom::Start(0))
|
|
.map_err(|error| error.to_string())?;
|
|
let mut digest = Sha256::new();
|
|
let mut buffer = [0u8; 1024 * 1024];
|
|
loop {
|
|
let count = file.read(&mut buffer).map_err(|error| error.to_string())?;
|
|
if count == 0 {
|
|
break;
|
|
}
|
|
digest.update(&buffer[..count]);
|
|
}
|
|
Ok(SectionSummary {
|
|
bytes: layout.section_bytes,
|
|
digest: digest.finalize().into(),
|
|
})
|
|
})();
|
|
if verified.is_err() {
|
|
let _ = fs::remove_file(destination);
|
|
}
|
|
verified
|
|
}
|
|
|
|
fn validate_shape(tensor: &Tensor<'_>) -> Result<u64, String> {
|
|
if !(1..=4).contains(&tensor.dims.len()) || tensor.source_dtype > 2 {
|
|
return Err(format!(
|
|
"{}: unsupported KAR dimensions or dtype",
|
|
tensor.name
|
|
));
|
|
}
|
|
let n = tensor
|
|
.dims
|
|
.iter()
|
|
.try_fold(1u64, |acc, dim| acc.checked_mul(*dim))
|
|
.ok_or("KAR tensor shape overflow")?;
|
|
if n == 0 {
|
|
return Err("KAR tensor has zero elements".into());
|
|
}
|
|
Ok(n)
|
|
}
|
|
|
|
fn validate_nested_slices(
|
|
name: &str,
|
|
layout: &NestedLayout,
|
|
group: u16,
|
|
scales: &[u16],
|
|
books: &[&[u16]],
|
|
planes: &[&[u32]],
|
|
) -> Result<(), String> {
|
|
if books.len() != planes.len() {
|
|
return Err(format!("{name}: level book count mismatch"));
|
|
}
|
|
if scales.len() as u64 != layout.n_padded / u64::from(group) {
|
|
return Err(format!("{name}: scale count mismatch"));
|
|
}
|
|
if scales.iter().any(|bits| bits & 0x7c00 == 0x7c00) {
|
|
return Err(format!("{name}: non-finite f16 scale"));
|
|
}
|
|
for (index, book) in books.iter().enumerate() {
|
|
if book.len() != 1usize << (index + 1) {
|
|
return Err(format!("{name}: level book size mismatch"));
|
|
}
|
|
if book.iter().any(|bits| bits & 0x7c00 == 0x7c00) {
|
|
return Err(format!("{name}: non-finite f16 codebook"));
|
|
}
|
|
}
|
|
if planes
|
|
.iter()
|
|
.any(|plane| plane.len() as u64 != layout.n_padded / 32)
|
|
{
|
|
return Err(format!("{name}: plane word count mismatch"));
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
fn push_cstr(destination: &mut Vec<u8>, value: &str) -> Result<(), String> {
|
|
if value.contains('\0') {
|
|
return Err("KAR names cannot contain NUL".into());
|
|
}
|
|
destination.extend_from_slice(value.as_bytes());
|
|
destination.push(0);
|
|
Ok(())
|
|
}
|
|
|
|
fn round_up(value: u64, alignment: u64) -> Result<u64, String> {
|
|
value
|
|
.div_ceil(alignment)
|
|
.checked_mul(alignment)
|
|
.ok_or("KAR aligned offset overflow".into())
|
|
}
|
|
|
|
fn nested_layout(
|
|
cursor: u64,
|
|
n_elements: u64,
|
|
group: u16,
|
|
nesting: u8,
|
|
planes_min: u8,
|
|
planes_max: u8,
|
|
levels: u8,
|
|
) -> Result<NestedLayout, String> {
|
|
let group = u64::from(group);
|
|
if group == 0
|
|
|| group > 1024
|
|
|| !group.is_multiple_of(32)
|
|
|| !(1..=16).contains(&levels)
|
|
|| nesting > 1
|
|
|| planes_min == 0
|
|
|| planes_min > planes_max
|
|
|| planes_max > levels
|
|
{
|
|
return Err("invalid nested KAR parameters".into());
|
|
}
|
|
let n_padded = n_elements
|
|
.div_ceil(group)
|
|
.checked_mul(group)
|
|
.ok_or("KAR padded size overflow")?;
|
|
let groups = n_padded / group;
|
|
let words = n_padded / 32;
|
|
let scales_bytes = groups.checked_mul(2).ok_or("KAR scales overflow")?;
|
|
let books_offset = round_up(
|
|
cursor
|
|
.checked_add(scales_bytes)
|
|
.ok_or("KAR scales overflow")?,
|
|
16,
|
|
)?;
|
|
let book_bytes = (1u64 << (levels as u32 + 2)) - 4;
|
|
let planes_offset = round_up(
|
|
books_offset
|
|
.checked_add(book_bytes)
|
|
.ok_or("KAR books overflow")?,
|
|
16,
|
|
)?;
|
|
let stride = round_up(words.checked_mul(4).ok_or("KAR plane size overflow")?, 16)?;
|
|
let plane_stride = u32::try_from(stride).map_err(|_| "KAR plane stride exceeds u32")?;
|
|
let end = planes_offset
|
|
.checked_add(
|
|
(levels as u64)
|
|
.checked_mul(stride)
|
|
.ok_or("KAR planes overflow")?,
|
|
)
|
|
.ok_or("KAR planes overflow")?;
|
|
let section_bytes = round_up(
|
|
end.checked_sub(cursor)
|
|
.ok_or("KAR section offset underflow")?,
|
|
256,
|
|
)?;
|
|
let payload_bits = (levels as u64)
|
|
.checked_mul(n_padded)
|
|
.and_then(|value| value.checked_add(groups.checked_mul(16)?))
|
|
.ok_or("KAR payload bit count overflow")?;
|
|
Ok(NestedLayout {
|
|
n_padded,
|
|
section_bytes,
|
|
scales_offset: cursor,
|
|
books_offset,
|
|
planes_offset,
|
|
plane_stride,
|
|
payload_bits,
|
|
})
|
|
}
|
|
|
|
fn write_section(file: &mut File, entry: &Placed<'_>) -> Result<u32, String> {
|
|
file.seek(SeekFrom::Start(entry.section_offset))
|
|
.map_err(|error| error.to_string())?;
|
|
let mut crc = !0u32;
|
|
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::NestedFile {
|
|
group,
|
|
levels,
|
|
path,
|
|
offset,
|
|
bytes,
|
|
digest,
|
|
..
|
|
} => {
|
|
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 nested source file is truncated".into());
|
|
}
|
|
validate_nested_file(&mut source, entry, *offset, *group, *levels)?;
|
|
source
|
|
.seek(SeekFrom::Start(*offset))
|
|
.map_err(|error| error.to_string())?;
|
|
let mut remaining = *bytes;
|
|
let mut buffer = vec![0u8; 1024 * 1024];
|
|
let mut actual_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())?;
|
|
actual_digest.update(&buffer[..count]);
|
|
write_bytes(file, &buffer[..count], &mut crc, &mut written)?;
|
|
remaining -= count as u64;
|
|
}
|
|
if actual_digest.finalize().as_slice() != *digest {
|
|
return Err(format!(
|
|
"{}: nested section digest mismatch",
|
|
entry.tensor.name
|
|
));
|
|
}
|
|
}
|
|
TensorData::Nested {
|
|
scales,
|
|
books,
|
|
planes,
|
|
..
|
|
} => {
|
|
for value in *scales {
|
|
write_bytes(file, &value.to_le_bytes(), &mut crc, &mut written)?;
|
|
}
|
|
pad_to(
|
|
file,
|
|
entry.books_offset - entry.section_offset,
|
|
&mut crc,
|
|
&mut written,
|
|
)?;
|
|
for book in *books {
|
|
for value in *book {
|
|
write_bytes(file, &value.to_le_bytes(), &mut crc, &mut written)?;
|
|
}
|
|
}
|
|
pad_to(
|
|
file,
|
|
entry.planes_offset - entry.section_offset,
|
|
&mut crc,
|
|
&mut written,
|
|
)?;
|
|
for plane in *planes {
|
|
let base = written;
|
|
for value in *plane {
|
|
write_bytes(file, &value.to_le_bytes(), &mut crc, &mut written)?;
|
|
}
|
|
pad_to(
|
|
file,
|
|
base + entry.plane_stride as u64,
|
|
&mut crc,
|
|
&mut written,
|
|
)?;
|
|
}
|
|
}
|
|
}
|
|
pad_to(file, entry.section_bytes, &mut crc, &mut written)?;
|
|
Ok(!crc)
|
|
}
|
|
|
|
#[derive(Clone, Copy)]
|
|
enum RegionRule {
|
|
FiniteScale,
|
|
FiniteBook,
|
|
ZeroPadding,
|
|
}
|
|
|
|
fn validate_nested_file(
|
|
source: &mut File,
|
|
entry: &Placed<'_>,
|
|
source_offset: u64,
|
|
group: u16,
|
|
levels: u8,
|
|
) -> Result<(), String> {
|
|
let scales_bytes = (entry.n_padded / u64::from(group)) * 2;
|
|
let books_start = entry.books_offset - entry.section_offset;
|
|
let books_bytes = (1u64 << (u32::from(levels) + 2)) - 4;
|
|
let planes_start = entry.planes_offset - entry.section_offset;
|
|
let plane_bytes = (entry.n_padded / 32) * 4;
|
|
let stride = u64::from(entry.plane_stride);
|
|
check_file_region(source, source_offset, scales_bytes, RegionRule::FiniteScale)?;
|
|
check_file_region(
|
|
source,
|
|
source_offset + scales_bytes,
|
|
books_start - scales_bytes,
|
|
RegionRule::ZeroPadding,
|
|
)?;
|
|
check_file_region(
|
|
source,
|
|
source_offset + books_start,
|
|
books_bytes,
|
|
RegionRule::FiniteBook,
|
|
)?;
|
|
check_file_region(
|
|
source,
|
|
source_offset + books_start + books_bytes,
|
|
planes_start - books_start - books_bytes,
|
|
RegionRule::ZeroPadding,
|
|
)?;
|
|
for level in 0..u64::from(levels) {
|
|
check_file_region(
|
|
source,
|
|
source_offset + planes_start + level * stride + plane_bytes,
|
|
stride - plane_bytes,
|
|
RegionRule::ZeroPadding,
|
|
)?;
|
|
}
|
|
let used_end = planes_start + u64::from(levels) * stride;
|
|
check_file_region(
|
|
source,
|
|
source_offset + used_end,
|
|
entry.section_bytes - used_end,
|
|
RegionRule::ZeroPadding,
|
|
)?;
|
|
Ok(())
|
|
}
|
|
|
|
fn check_file_region(
|
|
source: &mut File,
|
|
offset: u64,
|
|
bytes: u64,
|
|
rule: RegionRule,
|
|
) -> Result<(), String> {
|
|
source
|
|
.seek(SeekFrom::Start(offset))
|
|
.map_err(|error| error.to_string())?;
|
|
let mut remaining = bytes;
|
|
let mut buffer = [0u8; 64 * 1024];
|
|
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())?;
|
|
match rule {
|
|
RegionRule::FiniteScale | RegionRule::FiniteBook => {
|
|
if buffer[..count]
|
|
.as_chunks::<2>()
|
|
.0
|
|
.iter()
|
|
.any(|pair| u16::from_le_bytes(*pair) & 0x7c00 == 0x7c00)
|
|
{
|
|
let name = if matches!(rule, RegionRule::FiniteScale) {
|
|
"scale"
|
|
} else {
|
|
"codebook"
|
|
};
|
|
return Err(format!("non-finite f16 {name} in nested file"));
|
|
}
|
|
}
|
|
RegionRule::ZeroPadding => {
|
|
if buffer[..count].iter().any(|byte| *byte != 0) {
|
|
return Err("nonzero padding in nested file".into());
|
|
}
|
|
}
|
|
}
|
|
remaining -= count as u64;
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
fn write_bytes(
|
|
file: &mut File,
|
|
bytes: &[u8],
|
|
crc: &mut u32,
|
|
written: &mut u64,
|
|
) -> Result<(), String> {
|
|
file.write_all(bytes).map_err(|error| error.to_string())?;
|
|
*crc = kar::crc32_step(*crc, bytes);
|
|
*written = written
|
|
.checked_add(bytes.len() as u64)
|
|
.ok_or("KAR section write overflow")?;
|
|
Ok(())
|
|
}
|
|
|
|
fn pad_to(file: &mut File, target: u64, crc: &mut u32, written: &mut u64) -> Result<(), String> {
|
|
if *written > target {
|
|
return Err("KAR section exceeds planned layout".into());
|
|
}
|
|
let zeros = [0u8; 4096];
|
|
while *written < target {
|
|
let count = (target - *written).min(zeros.len() as u64) as usize;
|
|
write_bytes(file, &zeros[..count], crc, written)?;
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
fn write_record(record: &mut [u8], entry: &Placed<'_>) -> Result<(), String> {
|
|
let tensor = entry.tensor;
|
|
put_u32(record, 0, entry.name_offset);
|
|
put_u16(
|
|
record,
|
|
4,
|
|
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(_) | TensorData::RawFile { .. }
|
|
));
|
|
for index in 0..4 {
|
|
put_u64(
|
|
record,
|
|
8 + index * 8,
|
|
tensor.dims.get(index).copied().unwrap_or(1),
|
|
);
|
|
}
|
|
record[41] = tensor.source_dtype;
|
|
let nested = match &tensor.data {
|
|
TensorData::Nested {
|
|
group,
|
|
nesting,
|
|
planes_min,
|
|
planes_max,
|
|
planes,
|
|
..
|
|
} => Some((
|
|
*group,
|
|
*nesting,
|
|
*planes_min,
|
|
*planes_max,
|
|
planes.len() as u8,
|
|
)),
|
|
TensorData::NestedFile {
|
|
group,
|
|
nesting,
|
|
planes_min,
|
|
planes_max,
|
|
levels,
|
|
..
|
|
} => Some((*group, *nesting, *planes_min, *planes_max, *levels)),
|
|
_ => None,
|
|
};
|
|
if let Some((group, nesting, planes_min, planes_max, levels)) = nested {
|
|
record[42] = levels;
|
|
record[43] = planes_min;
|
|
record[44] = planes_max;
|
|
record[45] = nesting;
|
|
put_u16(record, 46, group);
|
|
put_u64(record, 64, entry.scales_offset);
|
|
put_u64(
|
|
record,
|
|
72,
|
|
(entry.n_padded / u64::from(group))
|
|
.checked_mul(2)
|
|
.ok_or("KAR scales overflow")?,
|
|
);
|
|
put_u64(record, 80, entry.books_offset);
|
|
put_u64(record, 88, (1u64 << (u32::from(levels) + 2)) - 4);
|
|
put_u64(record, 96, entry.planes_offset);
|
|
put_u32(record, 104, entry.plane_stride);
|
|
}
|
|
put_u64(record, 48, entry.n_elements);
|
|
put_u64(record, 56, entry.n_padded);
|
|
put_u32(record, 108, entry.payload_crc32);
|
|
put_u64(record, 112, entry.section_offset);
|
|
put_u64(record, 120, entry.section_bytes);
|
|
record[128..160].copy_from_slice(&tensor.source_digest);
|
|
put_u64(record, 160, tensor.source_offset);
|
|
Ok(())
|
|
}
|
|
|
|
fn put_u16(bytes: &mut [u8], offset: usize, value: u16) {
|
|
bytes[offset..offset + 2].copy_from_slice(&value.to_le_bytes());
|
|
}
|
|
fn put_u32(bytes: &mut [u8], offset: usize, value: u32) {
|
|
bytes[offset..offset + 4].copy_from_slice(&value.to_le_bytes());
|
|
}
|
|
fn put_u64(bytes: &mut [u8], offset: usize, value: u64) {
|
|
bytes[offset..offset + 8].copy_from_slice(&value.to_le_bytes());
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn streams_canonical_nested_section_and_rejects_corruption() {
|
|
let source = SourceIdentity {
|
|
name: "nested-fixture",
|
|
architecture: "qwen35",
|
|
builder: "strata-next-test",
|
|
digest: Sha256::digest(b"source").into(),
|
|
total_elements: 32,
|
|
bytes: 6,
|
|
};
|
|
let book1 = [0xbc00, 0x3c00];
|
|
let book2 = [0xbe00, 0xb800, 0x3800, 0x3e00];
|
|
let books: [&[u16]; 2] = [&book1, &book2];
|
|
let plane1 = [0xaaaa_aaaa];
|
|
let plane2 = [0x5555_5555];
|
|
let planes: [&[u32]; 2] = [&plane1, &plane2];
|
|
let source_digest: [u8; 32] = Sha256::digest(b"weights").into();
|
|
let original =
|
|
std::env::temp_dir().join(format!("strata-nested-{}.kar", std::process::id()));
|
|
let streamed =
|
|
std::env::temp_dir().join(format!("strata-nested-stream-{}.kar", std::process::id()));
|
|
let spool =
|
|
std::env::temp_dir().join(format!("strata-nested-spool-{}.bin", std::process::id()));
|
|
let _ = fs::remove_file(&original);
|
|
let _ = fs::remove_file(&streamed);
|
|
let nested = [Tensor {
|
|
name: "expert",
|
|
dims: &[32],
|
|
source_dtype: 1,
|
|
source_digest,
|
|
source_offset: 0,
|
|
data: TensorData::Nested {
|
|
group: 32,
|
|
nesting: 0,
|
|
planes_min: 1,
|
|
planes_max: 2,
|
|
scales: &[0x3c00],
|
|
books: &books,
|
|
planes: &planes,
|
|
},
|
|
}];
|
|
write_archive(&original, &source, &nested).unwrap();
|
|
let reference = fs::read(&original).unwrap();
|
|
let section_offset =
|
|
u64::from_le_bytes(reference[256 + 112..256 + 120].try_into().unwrap()) as usize;
|
|
let section_bytes =
|
|
u64::from_le_bytes(reference[256 + 120..256 + 128].try_into().unwrap()) as usize;
|
|
let section = &reference[section_offset..section_offset + section_bytes];
|
|
let native_spool = std::env::temp_dir().join(format!(
|
|
"strata-nested-native-spool-{}.bin",
|
|
std::process::id()
|
|
));
|
|
let _ = fs::remove_file(&native_spool);
|
|
let native_section = write_nested_section(&native_spool, &nested[0]).unwrap();
|
|
assert_eq!(native_section.bytes, section_bytes as u64);
|
|
assert_eq!(fs::read(&native_spool).unwrap(), section);
|
|
let expected_digest: [u8; 32] = Sha256::digest(section).into();
|
|
assert_eq!(native_section.digest, expected_digest);
|
|
let mut spool_bytes = vec![0xabu8; 11];
|
|
spool_bytes.extend_from_slice(section);
|
|
fs::write(&spool, &spool_bytes).unwrap();
|
|
let digest: [u8; 32] = Sha256::digest(section).into();
|
|
let file_tensor = |digest| {
|
|
[Tensor {
|
|
name: "expert",
|
|
dims: &[32],
|
|
source_dtype: 1,
|
|
source_digest,
|
|
source_offset: 0,
|
|
data: TensorData::NestedFile {
|
|
group: 32,
|
|
nesting: 0,
|
|
planes_min: 1,
|
|
planes_max: 2,
|
|
levels: 2,
|
|
path: &spool,
|
|
offset: 11,
|
|
bytes: section_bytes as u64,
|
|
digest,
|
|
},
|
|
}]
|
|
};
|
|
write_archive(&streamed, &source, &file_tensor(digest)).unwrap();
|
|
assert_eq!(fs::read(&streamed).unwrap(), reference);
|
|
fs::remove_file(&streamed).unwrap();
|
|
|
|
spool_bytes[11] = 0;
|
|
spool_bytes[12] = 0x7c;
|
|
fs::write(&spool, &spool_bytes).unwrap();
|
|
assert!(
|
|
write_archive(&streamed, &source, &file_tensor(digest))
|
|
.unwrap_err()
|
|
.contains("non-finite f16 scale")
|
|
);
|
|
assert!(!streamed.exists());
|
|
spool_bytes[11..11 + section_bytes].copy_from_slice(section);
|
|
spool_bytes[13] = 1;
|
|
fs::write(&spool, &spool_bytes).unwrap();
|
|
assert!(
|
|
write_archive(&streamed, &source, &file_tensor(digest))
|
|
.unwrap_err()
|
|
.contains("nonzero padding")
|
|
);
|
|
assert!(!streamed.exists());
|
|
spool_bytes[11..11 + section_bytes].copy_from_slice(section);
|
|
fs::write(&spool, &spool_bytes).unwrap();
|
|
assert!(
|
|
write_archive(&streamed, &source, &file_tensor([0; 32]))
|
|
.unwrap_err()
|
|
.contains("nested section digest mismatch")
|
|
);
|
|
assert!(!streamed.exists());
|
|
fs::remove_file(original).unwrap();
|
|
fs::remove_file(spool).unwrap();
|
|
fs::remove_file(native_spool).unwrap();
|
|
}
|
|
|
|
#[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 consuming_writer_removes_staged_input_after_verified_copy() {
|
|
let raw = (0..32u32)
|
|
.flat_map(|value| (value as f32).to_le_bytes())
|
|
.collect::<Vec<_>>();
|
|
let root = std::env::temp_dir().join(format!("strata-kar-consume-{}", std::process::id()));
|
|
let _ = fs::remove_dir_all(&root);
|
|
fs::create_dir(&root).unwrap();
|
|
let input = root.join("section.bin");
|
|
let output = root.join("archive.kar");
|
|
fs::write(&input, &raw).unwrap();
|
|
let digest: [u8; 32] = Sha256::digest(&raw).into();
|
|
let source = SourceIdentity {
|
|
name: "synthetic",
|
|
architecture: "qwen35",
|
|
builder: "consume-test",
|
|
digest,
|
|
total_elements: 32,
|
|
bytes: raw.len() as u64,
|
|
};
|
|
let tensors = [Tensor {
|
|
name: "raw",
|
|
dims: &[32],
|
|
source_dtype: 0,
|
|
source_digest: digest,
|
|
source_offset: 0,
|
|
data: TensorData::RawFile {
|
|
path: &input,
|
|
offset: 0,
|
|
bytes: raw.len() as u64,
|
|
},
|
|
}];
|
|
let summary = write_archive_consuming_files(&output, &source, &tensors).unwrap();
|
|
assert!(!input.exists());
|
|
assert_eq!(kar::verify(&output).unwrap(), summary);
|
|
fs::remove_dir_all(root).unwrap();
|
|
}
|
|
|
|
#[test]
|
|
fn archive_bytes_match_pinned_koference_reference_writer() {
|
|
// Oracle: koference 806d2398, r08/code/kar_container.py, RAW + NESTED fixture.
|
|
let raw = (0..32)
|
|
.flat_map(|value| (value as f32).to_le_bytes())
|
|
.collect::<Vec<_>>();
|
|
let mut source_bytes = raw.clone();
|
|
source_bytes.extend_from_slice(b"weights");
|
|
let source = SourceIdentity {
|
|
name: "synthetic",
|
|
architecture: "qwen35",
|
|
builder: "kar_container.py/2",
|
|
digest: Sha256::digest(&source_bytes).into(),
|
|
total_elements: 64,
|
|
bytes: source_bytes.len() as u64,
|
|
};
|
|
let book1 = [0xbc00, 0x3c00];
|
|
let book2 = [0xbe00, 0xb800, 0x3800, 0x3e00];
|
|
let books: [&[u16]; 2] = [&book1, &book2];
|
|
let plane1 = [0xaaaa_aaaa];
|
|
let plane2 = [0x5555_5555];
|
|
let planes: [&[u32]; 2] = [&plane1, &plane2];
|
|
let tensors = [
|
|
Tensor {
|
|
name: "norm",
|
|
dims: &[32],
|
|
source_dtype: 0,
|
|
source_digest: Sha256::digest(&raw).into(),
|
|
source_offset: 0,
|
|
data: TensorData::Raw(&raw),
|
|
},
|
|
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 path =
|
|
std::env::temp_dir().join(format!("strata-kar-writer-{}.kar", std::process::id()));
|
|
let _ = fs::remove_file(&path);
|
|
let summary = write_archive(&path, &source, &tensors).unwrap();
|
|
assert_eq!(summary.archive_bytes, 1280);
|
|
assert_eq!(summary.tensor_count, 2);
|
|
assert_eq!(summary.accounted_bpw, 160.0);
|
|
let archive = fs::read(&path).unwrap();
|
|
assert_eq!(
|
|
hex::encode(Sha256::digest(&archive)),
|
|
"013d3daa3f8ee70feb7045eee29390cb51e16d2a8558444cc8d6cbb91918f4f2"
|
|
);
|
|
assert!(write_archive(&path, &source, &tensors).is_err());
|
|
let other = path.with_file_name(format!("strata-kar-stale-{}.kar", std::process::id()));
|
|
let stale = other.with_file_name(format!(
|
|
"{}.part",
|
|
other.file_name().unwrap().to_string_lossy()
|
|
));
|
|
fs::write(&stale, b"previous work").unwrap();
|
|
assert!(write_archive(&other, &source, &tensors).is_err());
|
|
assert_eq!(fs::read(&stale).unwrap(), b"previous work");
|
|
fs::remove_file(stale).unwrap();
|
|
let invalid = [Tensor {
|
|
name: "bad-scale",
|
|
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: &[0x7c00],
|
|
books: &books,
|
|
planes: &planes,
|
|
},
|
|
}];
|
|
assert!(
|
|
write_archive(&other, &source, &invalid)
|
|
.unwrap_err()
|
|
.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();
|
|
}
|
|
}
|