scripts/dev/split_module.py (lexer-based, with 16 self-tests) moves the top-level fn and impl items of 59 oversize module files in control-plane, desktop-core, model-format, gateway-text, leleka-memory, experimental-ref, context, serving-policy, tokenizer, backend-api, quant-core, harmony, igpu, libc-shim, npu-service and runtime-client into foo/<name>.rs groups of about 250 lines; types, constants, macros, nested modules and tests stay, every path stays valid through pub use re-exports, restricted visibilities keep their scope one level down, include paths and super:: paths are shifted. Not touched: leleka-runtime, cuda-driver, native-cpu-expert, sampler-ref and cpu-* (hot path, next wave) and the files kar-off-ab edits. The baseline drops from 311 to 263 oversize files and from 273,600 to about 233,000 lines; the path-include ratchet ignores dir/name.rs child declarations.
229 lines
7.0 KiB
Rust
229 lines
7.0 KiB
Rust
//! Moved out of the parent module by STRA-338: fn write_nested_section, fn validate_shape, fn validate_nested_slices, fn push_cstr, fn round_up, fn nested_layout.
|
|
|
|
#[allow(unused_imports)]
|
|
use super::*;
|
|
|
|
/// 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
|
|
}
|
|
|
|
pub(super) 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)
|
|
}
|
|
|
|
pub(super) 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(())
|
|
}
|
|
|
|
pub(super) 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(())
|
|
}
|
|
|
|
pub(super) fn round_up(value: u64, alignment: u64) -> Result<u64, String> {
|
|
value
|
|
.div_ceil(alignment)
|
|
.checked_mul(alignment)
|
|
.ok_or("KAR aligned offset overflow".into())
|
|
}
|
|
|
|
pub(super) 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,
|
|
})
|
|
}
|