diff --git a/crates/model-format/src/bulk_read/for_each_chunk.rs b/crates/model-format/src/bulk_read/for_each_chunk.rs index f4b4b5d7..817311b3 100644 --- a/crates/model-format/src/bulk_read/for_each_chunk.rs +++ b/crates/model-format/src/bulk_read/for_each_chunk.rs @@ -3,7 +3,8 @@ #[allow(unused_imports)] use super::*; -/// Read `file[start .. start + len]` in blocks on several threads and hand each block to `sink(absolute_offset, bytes)`. +/// Read `file[start .. start + len]` in blocks on several threads and hand each block to `sink(absolute_offset, +/// bytes)`. /// Blocks arrive in no particular order, from different threads; each covers a distinct range of at most `plan.chunk` /// bytes. The first error stops the others and is returned. pub fn for_each_chunk(file: &File, start: u64, len: u64, plan: Plan, sink: F) -> io::Result @@ -11,65 +12,20 @@ where F: Fn(u64, &[u8]) -> io::Result<()> + Sync, { let began = Instant::now(); - let file_len = file.metadata()?.len(); - if start.checked_add(len).is_none_or(|end| end > file_len) { - return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "the span is beyond the end of the file")); - } + let file_len = span_file_len(file, start, len)?; let chunk = (plan.chunk.max(ALIGN) / ALIGN * ALIGN) as u64; - let mut strategy = plan.strategy; - let mut direct = None; - if strategy == Strategy::Direct { - match open_direct(file) { - Ok(handle) => direct = Some(handle), - Err(_) => strategy = Strategy::Advise, - } - } + let (strategy, direct) = open_strategy(file, plan.strategy); if len == 0 { return Ok(Report { strategy, bytes: 0, elapsed: began.elapsed() }); } - // The block that reaches the file's last bytes may be shorter than its aligned length: `read_full` stops at the end. + // The block that reaches the file's last bytes may be shorter than its aligned length: `read_full` stops at the + // end. let threads = plan.threads.clamp(1, len.div_ceil(chunk) as usize); - let buffer_len = chunk as usize + 2 * ALIGN; - let mut buffers = Vec::with_capacity(threads); - for _ in 0..threads { - buffers.push(Aligned::new(buffer_len)?); - } - let mut shared = Shared { - file, - direct, - strategy, - start, - len, - file_len, - chunk, - ahead: plan.ahead, - next: AtomicU64::new(0), - advised_to: AtomicU64::new(start), - failure: Mutex::new(None), - sink: &sink, - }; - if strategy == Strategy::Advise { - // The first window before any reader asks. - shared.keep_ahead(start); - } - // A direct handle that the file system accepted at open but refuses at read (EINVAL): retry the first block - // once with the buffered strategy instead of failing the whole load. - if let (Some(direct), Strategy::Direct) = (&shared.direct, shared.strategy) { - let mut probe = Aligned::new(ALIGN)?; - let aligned = start - start % ALIGN as u64; - if read_full(direct, probe.bytes(), aligned).is_err() { - shared.direct = None; - shared.strategy = Strategy::Advise; - shared.keep_ahead(start); - } - } + let mut buffers = aligned_buffers(threads, chunk as usize + 2 * ALIGN)?; + let mut shared = Shared::new(file, (strategy, direct), (start, len, file_len, chunk), plan.ahead, &sink); + shared.begin(start)?; let used = shared.strategy; - thread::scope(|scope| { - let shared = &shared; - for buffer in buffers.iter_mut() { - scope.spawn(move || shared.worker(buffer)); - } - }); + run_readers(&shared, &mut buffers); if let Some(error) = shared.failure.into_inner().ok().flatten() { return Err(error); } @@ -79,6 +35,89 @@ where Ok(Report { strategy: used, bytes: len, elapsed: began.elapsed() }) } +/// The length of the file, once the span `[start, start + len)` is known to lie inside it. +fn span_file_len(file: &File, start: u64, len: u64) -> io::Result { + let file_len = file.metadata()?.len(); + if start.checked_add(len).is_none_or(|end| end > file_len) { + return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "the span is beyond the end of the file")); + } + Ok(file_len) +} + +/// One reader thread per buffer, until the span is read or a read fails. +fn run_readers io::Result<()> + Sync>(shared: &Shared<'_, F>, buffers: &mut [Aligned]) { + thread::scope(|scope| { + for buffer in buffers.iter_mut() { + scope.spawn(move || shared.worker(buffer)); + } + }); +} + +/// The strategy that will run and, for `Direct`, the handle it reads through (`Advise` where `O_DIRECT` is refused). +fn open_strategy(file: &File, strategy: Strategy) -> (Strategy, Option) { + if strategy != Strategy::Direct { + return (strategy, None); + } + match open_direct(file) { + Ok(handle) => (Strategy::Direct, Some(handle)), + Err(_) => (Strategy::Advise, None), + } +} + +fn aligned_buffers(count: usize, len: usize) -> io::Result> { + let mut buffers = Vec::with_capacity(count); + for _ in 0..count { + buffers.push(Aligned::new(len)?); + } + Ok(buffers) +} + +impl<'a, F: Fn(u64, &[u8]) -> io::Result<()> + Sync> Shared<'a, F> { + /// The shared state of a read of `span = (start, len, file_len, chunk)` with the strategy that was opened. + fn new( + file: &'a File, + (strategy, direct): (Strategy, Option), + (start, len, file_len, chunk): (u64, u64, u64, u64), + ahead: u64, + sink: &'a F, + ) -> Self { + Shared { + file, + direct, + strategy, + start, + len, + file_len, + chunk, + ahead, + next: AtomicU64::new(0), + advised_to: AtomicU64::new(start), + failure: Mutex::new(None), + sink, + } + } + + /// Before the readers start: the first `WILLNEED` window, and the probe of a direct handle. + fn begin(&mut self, start: u64) -> io::Result<()> { + if self.strategy == Strategy::Advise { + // The first window before any reader asks. + self.keep_ahead(start); + } + // A direct handle that the file system accepted at open but refuses at read (EINVAL): retry the first block + // once with the buffered strategy instead of failing the whole load. + if let (Some(direct), Strategy::Direct) = (&self.direct, self.strategy) { + let mut probe = Aligned::new(ALIGN)?; + let aligned = start - start % ALIGN as u64; + if read_full(direct, probe.bytes(), aligned).is_err() { + self.direct = None; + self.strategy = Strategy::Advise; + self.keep_ahead(start); + } + } + Ok(()) + } +} + /// Fill `dest` with `file[start .. start + dest.len()]`. pub fn read_into(file: &File, start: u64, dest: &mut [u8], plan: Plan) -> io::Result { let chunk = plan.chunk.max(ALIGN) / ALIGN * ALIGN; diff --git a/crates/model-format/src/bulk_read/impl_strategy.rs b/crates/model-format/src/bulk_read/impl_strategy.rs index f0f7a472..66010aad 100644 --- a/crates/model-format/src/bulk_read/impl_strategy.rs +++ b/crates/model-format/src/bulk_read/impl_strategy.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: impl Strategy, impl Plan, impl Default_for_Plan, impl Report, impl Aligned, fn open_direct .... +//! Moved out of the parent module by STRA-338: impl Strategy, impl Plan, impl Default_for_Plan, impl Report, impl +//! Aligned, fn open_direct .... #[allow(unused_imports)] use super::*; @@ -15,7 +16,8 @@ impl Strategy { impl Plan { /// The defaults, then the environment (`LELEKA_LOAD_READ=direct|advise|plain`, `LELEKA_LOAD_THREADS=N`, - /// `LELEKA_LOAD_CHUNK_MIB=N`, `LELEKA_LOAD_AHEAD_MIB=N`): the switches that let one binary be measured in each form. + /// `LELEKA_LOAD_CHUNK_MIB=N`, `LELEKA_LOAD_AHEAD_MIB=N`): the switches that let one binary be measured in each + /// form. pub fn from_env() -> Plan { Plan::with_overrides(Plan::default(), |name| std::env::var(name).ok()) } diff --git a/crates/model-format/src/gguf.rs b/crates/model-format/src/gguf.rs index 2a4f769d..67615cd2 100644 --- a/crates/model-format/src/gguf.rs +++ b/crates/model-format/src/gguf.rs @@ -196,6 +196,12 @@ pub use parse_artifact_digest::*; mod read_metadata_snapshot_with_architecture; #[allow(unused_imports)] pub use read_metadata_snapshot_with_architecture::*; +mod open_regular; +#[allow(unused_imports)] +pub use open_regular::*; +mod index_parse; +#[allow(unused_imports)] +pub use index_parse::*; mod read_index_file; #[allow(unused_imports)] pub use read_index_file::*; diff --git a/crates/model-format/src/gguf/impl_cursor.rs b/crates/model-format/src/gguf/impl_cursor.rs index 9532c98e..9e6d6dd3 100644 --- a/crates/model-format/src/gguf/impl_cursor.rs +++ b/crates/model-format/src/gguf/impl_cursor.rs @@ -79,13 +79,18 @@ impl Cursor { if count > 1_000_000 { return Err("unreasonable GGUF tokenizer array count".into()); } + self.strings(count, "GGUF tokenizer array size overflow", "GGUF tokenizer array exceeds 512 MiB") + } + + /// `count` strings whose total length stays below 512 MiB; the messages name the array kind that failed. + fn strings(&mut self, count: u64, overflow: &'static str, exceeds: &'static str) -> Result> { let mut total = 0u64; let mut values = Vec::with_capacity(count as usize); for _ in 0..count { let value = self.string()?; - total = total.checked_add(value.len() as u64).ok_or("GGUF tokenizer array size overflow")?; + total = total.checked_add(value.len() as u64).ok_or(overflow)?; if total > 512 * 1024 * 1024 { - return Err("GGUF tokenizer array exceeds 512 MiB".into()); + return Err(exceeds.into()); } values.push(value); } @@ -96,11 +101,7 @@ impl Cursor { if kind != 9 { return Err("expected a GGUF integer array".into()); } - let element = self.u32()?; - let count = self.u64()?; - if count > 1_000_000 { - return Err("unreasonable GGUF tokenizer array count".into()); - } + let (element, count) = self.array_header("unreasonable GGUF tokenizer array count")?; let mut values = Vec::with_capacity(count as usize); for _ in 0..count { values.push(self.integer(element)?); @@ -108,109 +109,96 @@ impl Cursor { Ok(values) } + /// The element type and the element count of an array value; `too_many` is the refusal for more than 1M elements. + fn array_header(&mut self, too_many: &'static str) -> Result<(u32, u64)> { + let element = self.u32()?; + let count = self.u64()?; + if count > 1_000_000 { + return Err(too_many.into()); + } + Ok((element, count)) + } + pub(super) fn integer(&mut self, kind: u32) -> Result { match kind { 0 | 7 => Ok(u32::from(self.u8()?)), - 1 => u32::try_from(self.u8()? as i8).map_err(Into::into), 2 => Ok(u32::from(self.u16()?)), - 3 => u32::try_from(self.u16()? as i16).map_err(Into::into), 4 => self.u32(), - 5 => u32::try_from(self.u32()? as i32).map_err(Into::into), + 1 | 3 | 5 | 11 => u32::try_from(self.signed_scalar(kind)?).map_err(Into::into), 10 => u32::try_from(self.u64()?).map_err(Into::into), - 11 => u32::try_from(self.u64()? as i64).map_err(Into::into), _ => Err(format!("GGUF metadata type {kind} is not an integer").into()), } } - pub(super) fn metadata_value(&mut self, kind: u32) -> Result { + /// An unsigned scalar of kind 0, 2, 4 or 10. + fn unsigned_scalar(&mut self, kind: u32) -> Result { Ok(match kind { - 0 => MetadataValue::Unsigned(u64::from(self.u8()?)), - 7 => MetadataValue::Boolean(self.u8()? != 0), - 1 => MetadataValue::Signed(i64::from(self.u8()? as i8)), - 2 => MetadataValue::Unsigned(u64::from(self.u16()?)), - 3 => MetadataValue::Signed(i64::from(self.u16()? as i16)), - 4 => MetadataValue::Unsigned(u64::from(self.u32()?)), - 5 => MetadataValue::Signed(i64::from(self.u32()? as i32)), - 6 => MetadataValue::Float(f64::from(f32::from_bits(self.u32()?))), - 8 => MetadataValue::Text(self.string()?), - 9 => self.metadata_array()?, - 10 => MetadataValue::Unsigned(self.u64()?), - 11 => MetadataValue::Signed(self.u64()? as i64), - 12 => MetadataValue::Float(f64::from_bits(self.u64()?)), - _ => return Err(format!("unknown GGUF metadata type {kind}").into()), + 0 => u64::from(self.u8()?), + 2 => u64::from(self.u16()?), + 4 => u64::from(self.u32()?), + 10 => self.u64()?, + _ => unreachable!(), }) } - pub(super) fn metadata_array(&mut self) -> Result { - let element = self.u32()?; - let count = self.u64()?; - if count > 1_000_000 { - return Err("unreasonable GGUF metadata array count".into()); + /// A signed scalar of kind 1, 3, 5 or 11. + fn signed_scalar(&mut self, kind: u32) -> Result { + Ok(match kind { + 1 => i64::from(self.u8()? as i8), + 3 => i64::from(self.u16()? as i16), + 5 => i64::from(self.u32()? as i32), + 11 => self.u64()? as i64, + _ => unreachable!(), + }) + } + + /// A float scalar of kind 6 (f32) or 12 (f64). + fn float_scalar(&mut self, kind: u32) -> Result { + Ok(if kind == 6 { f64::from(f32::from_bits(self.u32()?)) } else { f64::from_bits(self.u64()?) }) + } + + fn boolean(&mut self) -> Result { + Ok(self.u8()? != 0) + } + + pub(super) fn metadata_value(&mut self, kind: u32) -> Result { + match kind { + 0 | 2 | 4 | 10 => self.unsigned_scalar(kind).map(MetadataValue::Unsigned), + 1 | 3 | 5 | 11 => self.signed_scalar(kind).map(MetadataValue::Signed), + 6 | 12 => self.float_scalar(kind).map(MetadataValue::Float), + 7 => self.boolean().map(MetadataValue::Boolean), + 8 => self.string().map(MetadataValue::Text), + 9 => self.metadata_array(), + _ => Err(format!("unknown GGUF metadata type {kind}").into()), } - let capacity = count as usize; + } + + pub(super) fn metadata_array(&mut self) -> Result { + let (element, count) = self.array_header("unreasonable GGUF metadata array count")?; match element { - 7 => { - let mut values = Vec::with_capacity(capacity); - for _ in 0..count { - values.push(self.u8()? != 0); - } - Ok(MetadataValue::BooleanArray(values)) - } + 7 => self.repeat(count, Self::boolean).map(MetadataValue::BooleanArray), 0 | 2 | 4 | 10 => { - let mut values = Vec::with_capacity(capacity); - for _ in 0..count { - values.push(match element { - 0 => u64::from(self.u8()?), - 2 => u64::from(self.u16()?), - 4 => u64::from(self.u32()?), - 10 => self.u64()?, - _ => unreachable!(), - }); - } - Ok(MetadataValue::UnsignedArray(values)) - } - 1 | 3 | 5 | 11 => { - let mut values = Vec::with_capacity(capacity); - for _ in 0..count { - values.push(match element { - 1 => i64::from(self.u8()? as i8), - 3 => i64::from(self.u16()? as i16), - 5 => i64::from(self.u32()? as i32), - 11 => self.u64()? as i64, - _ => unreachable!(), - }); - } - Ok(MetadataValue::SignedArray(values)) - } - 6 | 12 => { - let mut values = Vec::with_capacity(capacity); - for _ in 0..count { - values.push(if element == 6 { - f64::from(f32::from_bits(self.u32()?)) - } else { - f64::from_bits(self.u64()?) - }); - } - Ok(MetadataValue::FloatArray(values)) - } - 8 => { - let mut total = 0u64; - let mut values = Vec::with_capacity(capacity); - for _ in 0..count { - let value = self.string()?; - total = total.checked_add(value.len() as u64).ok_or("GGUF metadata array size overflow")?; - if total > 512 * 1024 * 1024 { - return Err("GGUF metadata string array exceeds 512 MiB".into()); - } - values.push(value); - } - Ok(MetadataValue::TextArray(values)) + self.repeat(count, |this| this.unsigned_scalar(element)).map(MetadataValue::UnsignedArray) } + 1 | 3 | 5 | 11 => self.repeat(count, |this| this.signed_scalar(element)).map(MetadataValue::SignedArray), + 6 | 12 => self.repeat(count, |this| this.float_scalar(element)).map(MetadataValue::FloatArray), + 8 => self + .strings(count, "GGUF metadata array size overflow", "GGUF metadata string array exceeds 512 MiB") + .map(MetadataValue::TextArray), 9 => Err("nested GGUF arrays are unsupported".into()), _ => Err(format!("invalid GGUF metadata array element type {element}").into()), } } + /// `count` values, each read by `read`. + fn repeat(&mut self, count: u64, mut read: impl FnMut(&mut Self) -> Result) -> Result> { + let mut values = Vec::with_capacity(count as usize); + for _ in 0..count { + values.push(read(self)?); + } + Ok(values) + } + pub(super) fn skip_value(&mut self, kind: u32) -> Result<()> { match kind { 0 | 1 | 7 => self.skip(1), @@ -220,26 +208,49 @@ impl Cursor { let size = self.u64()?; self.skip(size) } - 9 => { - let element = self.u32()?; - let count = self.u64()?; - match element { - 8 => { - if count > 10_000_000 { - return Err("unreasonable GGUF string array count".into()); - } - for _ in 0..count { - let size = self.u64()?; - self.skip(size)?; - } - Ok(()) - } - 9 => Err("nested GGUF arrays are unsupported".into()), - _ => self.skip(count.checked_mul(value_width(element)?).ok_or("GGUF array size overflow")?), - } - } + 9 => self.skip_array(), 10..=12 => self.skip(8), _ => Err(format!("unknown GGUF metadata type {kind}").into()), } } + + fn skip_array(&mut self) -> Result<()> { + let element = self.u32()?; + let count = self.u64()?; + match element { + 8 => self.skip_strings(count), + 9 => Err("nested GGUF arrays are unsupported".into()), + _ => self.skip(count.checked_mul(value_width(element)?).ok_or("GGUF array size overflow")?), + } + } + + fn skip_strings(&mut self, count: u64) -> Result<()> { + if count > 10_000_000 { + return Err("unreasonable GGUF string array count".into()); + } + for _ in 0..count { + let size = self.u64()?; + self.skip(size)?; + } + Ok(()) + } + + /// The number of metadata entries of the header, after the magic, the version and the tensor count. + pub(super) fn metadata_count(&mut self) -> Result { + self.skip(16)?; // magic, version, tensor count + let count = self.u64()?; + if count > 1_000_000 { + return Err("unreasonable GGUF header count".into()); + } + Ok(count) + } + + /// The key and the value type of the next metadata entry; a key that `seen` already holds is refused. + pub(super) fn entry_header(&mut self, seen: &mut HashSet) -> Result<(String, u32)> { + let key = self.string()?; + if !seen.insert(key.clone()) { + return Err(format!("duplicate GGUF metadata key: {key}").into()); + } + Ok((key, self.u32()?)) + } } diff --git a/crates/model-format/src/gguf/impl_verifiedgguffile.rs b/crates/model-format/src/gguf/impl_verifiedgguffile.rs index b28b85d2..e5db83d7 100644 --- a/crates/model-format/src/gguf/impl_verifiedgguffile.rs +++ b/crates/model-format/src/gguf/impl_verifiedgguffile.rs @@ -11,39 +11,11 @@ impl VerifiedGgufFile { /// The opened file's contents must remain stable until this handle is dropped. pub fn open(path: &Path, expected_digest: &str) -> Result { let expected = parse_artifact_digest(expected_digest)?; - // Refuse an ordinary nonregular path before opening it (notably FIFOs). - // The opened-file check below is authoritative for the accepted source. - if !std::fs::metadata(path)?.is_file() { - return Err("GGUF source must be a regular file".into()); - } - let mut file = File::open(path)?; - let metadata = file.metadata()?; - if !metadata.is_file() { - return Err("GGUF source must be a regular file".into()); - } + let (mut file, metadata) = open_regular_file(path)?; let size = metadata.len(); - let identity = crate::verify_stamp::FileIdentity::of(&metadata); - let stamps = crate::verify_stamp::global(); - // A stamp skips the hash only for this very file in this very state, keyed by the pinned digest. - let trusted = matches!((stamps, identity.as_ref()), (Some(s), Some(id)) if s.trusts("gguf", &expected, id)); - let actual: [u8; 32] = if trusted { expected } else { sha256_pipelined(&file, size)? }; - if actual != expected { - return Err("GGUF artifact SHA256 mismatch".into()); - } - if file.metadata()?.len() != size { - return Err("GGUF source size changed during verification".into()); - } - if !trusted - && let (Some(stamps), Some(before)) = (stamps, identity) - && crate::verify_stamp::FileIdentity::of(&file.metadata()?) == Some(before) - { - // Only a file that did not change while it was hashed can vouch for itself next time. - let _ = stamps.record("gguf", &expected, &before); - } + let actual = verify_digest(&file, &metadata, &expected)?; let index = read_index_file(&mut file, size, true)?; - if file.metadata()?.len() != size { - return Err("GGUF source size changed during indexing".into()); - } + ensure_size(&file, size, "GGUF source size changed during indexing")?; Ok(Self { file, index, artifact_sha256: actual, resident_source_id: None }) } @@ -113,20 +85,7 @@ impl VerifiedGgufFile { bytes: u64, consume: impl FnMut(&[u8]) -> std::io::Result<()>, ) -> Result<()> { - let tensor = self.index.tensors.get(tensor_number).ok_or("GGUF tensor index is out of bounds")?; - if tensor.bytes == 0 || offset.checked_add(bytes).is_none_or(|end| end > tensor.bytes) { - return Err("GGUF tensor byte range is out of bounds".into()); - } - let absolute = self - .index - .summary - .data_start - .checked_add(tensor.offset) - .and_then(|start| start.checked_add(offset)) - .ok_or("GGUF tensor offset overflow")?; - if absolute.checked_add(bytes).is_none_or(|end| end > self.index.summary.file_size) { - return Err("GGUF tensor exceeds indexed file".into()); - } + let absolute = self.absolute_span(tensor_number, offset, bytes)?; self.check_size()?; // Cached descriptor validation admits an empty span. Preserve both // same-FD size checks without moving the retained reader's cursor. @@ -152,20 +111,7 @@ impl VerifiedGgufFile { /// FD, indexed bounds and pre/post size observations; every byte of `bytes` is written on success. pub(crate) fn read_tensor_into(&mut self, tensor_number: usize, offset: u64, bytes: &mut [u8]) -> Result<()> { let length = u64::try_from(bytes.len())?; - let tensor = self.index.tensors.get(tensor_number).ok_or("GGUF tensor index is out of bounds")?; - if tensor.bytes == 0 || offset.checked_add(length).is_none_or(|end| end > tensor.bytes) { - return Err("GGUF tensor byte range is out of bounds".into()); - } - let absolute = self - .index - .summary - .data_start - .checked_add(tensor.offset) - .and_then(|start| start.checked_add(offset)) - .ok_or("GGUF tensor offset overflow")?; - if absolute.checked_add(length).is_none_or(|end| end > self.index.summary.file_size) { - return Err("GGUF tensor exceeds indexed file".into()); - } + let absolute = self.absolute_span(tensor_number, offset, length)?; self.check_size()?; // Original empty stream does not seek or invoke a consumer. if length != 0 { @@ -187,9 +133,58 @@ impl VerifiedGgufFile { } pub(super) fn check_size(&self) -> Result<()> { - if self.file.metadata()?.len() != self.index.summary.file_size { - return Err("GGUF source size changed after verification".into()); + ensure_size(&self.file, self.index.summary.file_size, "GGUF source size changed after verification") + } + + /// The absolute file offset of `length` bytes at `offset` within an indexed tensor, after the bounds checks. + fn absolute_span(&self, tensor_number: usize, offset: u64, length: u64) -> Result { + let tensor = self.index.tensors.get(tensor_number).ok_or("GGUF tensor index is out of bounds")?; + if tensor.bytes == 0 || offset.checked_add(length).is_none_or(|end| end > tensor.bytes) { + return Err("GGUF tensor byte range is out of bounds".into()); } - Ok(()) + let absolute = self + .index + .summary + .data_start + .checked_add(tensor.offset) + .and_then(|start| start.checked_add(offset)) + .ok_or("GGUF tensor offset overflow")?; + if absolute.checked_add(length).is_none_or(|end| end > self.index.summary.file_size) { + return Err("GGUF tensor exceeds indexed file".into()); + } + Ok(absolute) } } + +/// Hash the whole file against `expected`, or trust a verification stamp for this very file in this very state. +fn verify_digest(file: &File, metadata: &std::fs::Metadata, expected: &[u8; 32]) -> Result<[u8; 32]> { + let size = metadata.len(); + let identity = crate::verify_stamp::FileIdentity::of(metadata); + let stamps = crate::verify_stamp::global(); + // A stamp skips the hash only for this very file in this very state, keyed by the pinned digest. + let trusted = matches!((stamps, identity.as_ref()), (Some(s), Some(id)) if s.trusts("gguf", expected, id)); + let actual: [u8; 32] = if trusted { *expected } else { sha256_pipelined(file, size)? }; + if actual != *expected { + return Err("GGUF artifact SHA256 mismatch".into()); + } + ensure_size(file, size, "GGUF source size changed during verification")?; + if !trusted { + record_stamp(file, stamps, identity, expected)?; + } + Ok(actual) +} + +fn record_stamp( + file: &File, + stamps: Option<&crate::verify_stamp::VerifyStamps>, + identity: Option, + expected: &[u8; 32], +) -> Result<()> { + if let (Some(stamps), Some(before)) = (stamps, identity) + && crate::verify_stamp::FileIdentity::of(&file.metadata()?) == Some(before) + { + // Only a file that did not change while it was hashed can vouch for itself next time. + let _ = stamps.record("gguf", expected, &before); + } + Ok(()) +} diff --git a/crates/model-format/src/gguf/index_parse.rs b/crates/model-format/src/gguf/index_parse.rs new file mode 100644 index 00000000..e542e521 --- /dev/null +++ b/crates/model-format/src/gguf/index_parse.rs @@ -0,0 +1,254 @@ +//! The GGUF v3 header walk shared by the owned reader and the provisional capture reader. + +#[allow(unused_imports)] +use super::*; + +/// What differs between the two readers: which header counts are reasonable and how `general.alignment` is read. +pub(super) struct IndexRules { + pub(super) counts_ok: fn(tensors: u64, metadata: u64) -> bool, + pub(super) reject_wide_alignment: bool, +} + +/// The metadata keys the index keeps. +struct MetadataFields { + architecture: Option, + split_no: Option, + split_count: Option, + split_tensors_count: Option, + alignment: u64, +} + +impl MetadataFields { + fn new() -> Self { + Self { architecture: None, split_no: None, split_count: None, split_tensors_count: None, alignment: 32 } + } + + fn apply( + &mut self, + cursor: &mut Cursor, + key: &str, + kind: u32, + rules: &IndexRules, + ) -> Result<()> { + match key { + "general.architecture" | "general.alignment" => self.apply_general(cursor, key, kind, rules), + "split.no" | "split.count" | "split.tensors.count" => self.apply_split(cursor, key, kind), + _ => cursor.skip_value(kind), + } + } + + fn apply_general( + &mut self, + cursor: &mut Cursor, + key: &str, + kind: u32, + rules: &IndexRules, + ) -> Result<()> { + match (key, kind) { + ("general.architecture", 8) => self.architecture = Some(cursor.string()?), + ("general.alignment", 4) => self.alignment = u64::from(cursor.u32()?), + ("general.alignment", _) if rules.reject_wide_alignment => { + // tools/gguf_reader.py accepts any integer width; llama.cpp and the C++ engine read a uint32. + // Silently keeping the default would place the data section at the wrong byte. + return Err("general.alignment must be a uint32".into()); + } + _ => cursor.skip_value(kind)?, + } + Ok(()) + } + + fn apply_split(&mut self, cursor: &mut Cursor, key: &str, kind: u32) -> Result<()> { + match (key, kind) { + ("split.no", 2) => self.split_no = Some(u64::from(cursor.u16()?)), + ("split.count", 2) => self.split_count = Some(u64::from(cursor.u16()?)), + ("split.tensors.count", 5) => self.split_tensors_count = Some(read_split_tensors_count(cursor)?), + _ => return Err("GGUF split metadata has an invalid integer type".into()), + } + Ok(()) + } + + fn into_summary( + self, + tensors: u64, + metadata: u64, + data_start: u64, + size: u64, + types: BTreeMap, + ) -> Summary { + Summary { + tensors, + metadata, + architecture: self.architecture, + split_no: self.split_no, + split_count: self.split_count, + split_tensors_count: self.split_tensors_count, + data_start, + file_size: size, + types, + } + } + + fn check_split(&self) -> Result<()> { + if let (Some(no), Some(count)) = (self.split_no, self.split_count) + && (count == 0 || no >= count) + { + return Err("invalid GGUF split metadata".into()); + } + Ok(()) + } +} + +pub(super) fn parse_index( + cursor: &mut Cursor, + size: u64, + strict: bool, + rules: &IndexRules, +) -> Result { + let (tensors, metadata) = read_counts(cursor, rules)?; + let fields = read_metadata(cursor, metadata, rules)?; + let (mut tensor_index, types) = read_tensor_infos(cursor, tensors)?; + let data_start = data_section_start(cursor.position()?, fields.alignment, size)?; + check_tensor_offsets(&tensor_index, data_start, fields.alignment, size)?; + if strict { + assign_byte_counts(&mut tensor_index, size, data_start, fields.alignment)?; + } + fields.check_split()?; + let summary = fields.into_summary(tensors, metadata, data_start, size, types); + Ok(TensorIndex { summary, tensors: tensor_index }) +} + +/// The magic, the version and the two counts: (tensors, metadata entries). +fn read_counts(cursor: &mut Cursor, rules: &IndexRules) -> Result<(u64, u64)> { + if cursor.take(4)? != b"GGUF" { + return Err("not a GGUF file".into()); + } + if cursor.u32()? != 3 { + return Err("only GGUF v3 is supported".into()); + } + let tensors = cursor.u64()?; + let metadata = cursor.u64()?; + if !(rules.counts_ok)(tensors, metadata) { + return Err("unreasonable GGUF header count".into()); + } + Ok((tensors, metadata)) +} + +fn read_split_tensors_count(cursor: &mut Cursor) -> Result { + let count = cursor.u32()?; + if count > i32::MAX as u32 { + return Err("negative GGUF split tensor count".into()); + } + Ok(u64::from(count)) +} + +fn read_metadata(cursor: &mut Cursor, count: u64, rules: &IndexRules) -> Result { + let mut fields = MetadataFields::new(); + let mut keys = HashSet::new(); + for _ in 0..count { + let (key, kind) = cursor.entry_header(&mut keys)?; + fields.apply(cursor, &key, kind, rules)?; + } + if !fields.alignment.is_power_of_two() || fields.alignment > 4096 { + return Err("invalid GGUF alignment".into()); + } + Ok(fields) +} + +fn read_tensor_infos( + cursor: &mut Cursor, + count: u64, +) -> Result<(Vec, BTreeMap)> { + let mut types = BTreeMap::new(); + let mut names = HashSet::new(); + let mut tensor_index = Vec::with_capacity(count as usize); + for _ in 0..count { + let name = cursor.string()?; + if !names.insert(name.clone()) { + return Err("duplicate GGUF tensor name".into()); + } + let dimensions = read_shape(cursor)?; + let kind = cursor.u32()?; + let offset = cursor.u64()?; + *types.entry(kind).or_insert(0) += 1; + tensor_index.push(TensorInfo { name, dimensions, kind, offset, bytes: 0 }); + } + Ok((tensor_index, types)) +} + +fn read_shape(cursor: &mut Cursor) -> Result> { + let dimensions = cursor.u32()?; + if !(1..=8).contains(&dimensions) { + return Err("invalid GGUF tensor dimensions".into()); + } + let mut shape = Vec::with_capacity(dimensions as usize); + for _ in 0..dimensions { + let dim = cursor.u64()?; + if dim == 0 { + return Err("zero GGUF tensor dimension".into()); + } + shape.push(dim); + } + Ok(shape) +} + +fn data_section_start(header_end: u64, alignment: u64, size: u64) -> Result { + let data_start = + header_end.checked_add(alignment - 1).ok_or("GGUF header offset overflow")? / alignment * alignment; + if data_start > size { + return Err("GGUF data section is truncated".into()); + } + Ok(data_start) +} + +fn check_tensor_offsets(tensors: &[TensorInfo], data_start: u64, alignment: u64, size: u64) -> Result<()> { + for tensor in tensors { + if tensor.offset % alignment != 0 || data_start.checked_add(tensor.offset).is_none_or(|start| start >= size) { + return Err("GGUF tensor offset is out of bounds or unaligned".into()); + } + } + Ok(()) +} + +/// Strict mode: the tensors tile the data section in offset order, and each gets its byte count. +fn assign_byte_counts(tensors: &mut [TensorInfo], size: u64, data_start: u64, alignment: u64) -> Result<()> { + let mut positions = (0..tensors.len()).collect::>(); + if positions.is_empty() { + return Err("GGUF has no tensors to index".into()); + } + positions.sort_unstable_by_key(|&index| tensors[index].offset); + if tensors[positions[0]].offset != 0 { + return Err("GGUF first tensor does not start at data offset zero".into()); + } + for (at, &index) in positions.iter().enumerate() { + let bytes = tensor_byte_count(&tensors[index])?; + let next = positions.get(at + 1).map(|&next| tensors[next].offset).unwrap_or(size - data_start); + check_extent(&tensors[index], bytes, next, alignment)?; + tensors[index].bytes = bytes; + } + Ok(()) +} + +fn tensor_byte_count(tensor: &TensorInfo) -> Result { + let (block_elements, block_bytes) = + block_geometry(tensor.kind).ok_or_else(|| format!("unsupported GGUF tensor type {}", tensor.kind))?; + let elements = tensor + .dimensions + .iter() + .try_fold(1u64, |product, dim| product.checked_mul(*dim)) + .ok_or("GGUF tensor element count overflow")?; + if tensor.dimensions[0] % block_elements != 0 { + return Err(format!("{}: tensor row is not block aligned", tensor.name).into()); + } + Ok(elements + .checked_div(block_elements) + .and_then(|blocks| blocks.checked_mul(block_bytes)) + .ok_or("GGUF tensor byte count overflow")?) +} + +fn check_extent(tensor: &TensorInfo, bytes: u64, next: u64, alignment: u64) -> Result<()> { + let end = tensor.offset.checked_add(bytes).ok_or("GGUF tensor end overflow")?; + if end > next || next - end >= alignment { + return Err(format!("{}: tensor bytes overlap or have an invalid gap", tensor.name).into()); + } + Ok(()) +} diff --git a/crates/model-format/src/gguf/open_regular.rs b/crates/model-format/src/gguf/open_regular.rs new file mode 100644 index 00000000..ea871c53 --- /dev/null +++ b/crates/model-format/src/gguf/open_regular.rs @@ -0,0 +1,27 @@ +//! Opening a GGUF source for verification: the regular-file checks and the same-descriptor size observation. + +#[allow(unused_imports)] +use super::*; + +/// Open `path`, refusing anything that is not a regular file; returns the file and its metadata. +pub(super) fn open_regular_file(path: &Path) -> Result<(File, std::fs::Metadata)> { + // Refuse an ordinary nonregular path before opening it (notably FIFOs). + // The opened-file check below is authoritative for the accepted source. + if !std::fs::metadata(path)?.is_file() { + return Err("GGUF source must be a regular file".into()); + } + let file = File::open(path)?; + let metadata = file.metadata()?; + if !metadata.is_file() { + return Err("GGUF source must be a regular file".into()); + } + Ok((file, metadata)) +} + +/// The open file must still have `size` bytes; `message` names the phase that observed a change. +pub(super) fn ensure_size(file: &File, size: u64, message: &'static str) -> Result<()> { + if file.metadata()?.len() != size { + return Err(message.into()); + } + Ok(()) +} diff --git a/crates/model-format/src/gguf/parse_artifact_digest.rs b/crates/model-format/src/gguf/parse_artifact_digest.rs index af062020..1d89241a 100644 --- a/crates/model-format/src/gguf/parse_artifact_digest.rs +++ b/crates/model-format/src/gguf/parse_artifact_digest.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: fn parse_artifact_digest, fn sha256_pipelined, fn stream_file_span, fn read_file_span_owned, fn read_file_span_into, fn check_flash_next_profile .... +//! Moved out of the parent module by STRA-338: fn parse_artifact_digest, fn sha256_pipelined, fn stream_file_span, fn +//! read_file_span_owned, fn read_file_span_into, fn check_flash_next_profile .... #[allow(unused_imports)] use super::*; @@ -93,33 +94,9 @@ pub(super) fn validate_flash_next_profile(snapshot: &MetadataSnapshot) -> Result if snapshot.architecture.as_deref() != Some("qwen4exp") { return Err("runtime_profile requires general.architecture=qwen4exp".into()); } - let required = [ - ("qwen4exp.block_count", Some(48)), - ("qwen4exp.embedding_length", Some(2560)), - ("qwen4exp.attention.head_count", Some(24)), - ("qwen4exp.attention.head_count_kv", Some(2)), - ("qwen4exp.expert_count", None), - ("qwen4exp.expert_used_count", None), - ]; let mut values = BTreeMap::new(); - for (key, expected) in required { - let value = match snapshot.values.get(key) { - Some(MetadataValue::Unsigned(value)) => u32::try_from(*value) - .map_err(|_| format!("runtime_profile: {key} must be a nonnegative 32-bit integer"))?, - Some(MetadataValue::Signed(value)) => u32::try_from(*value) - .map_err(|_| format!("runtime_profile: {key} must be a nonnegative 32-bit integer"))?, - None => return Err(format!("runtime_profile: missing {key}").into()), - _ => return Err(format!("runtime_profile: {key} must be an integer").into()), - }; - values.insert(key, value); - if value == 0 || value > i32::MAX as u32 { - return Err(format!("runtime_profile: {key} must be in 1..2147483647").into()); - } - if let Some(expected) = expected - && value != expected - { - return Err(format!("runtime_profile: {key}={value}, expected {expected}").into()); - } + for (key, expected) in FLASH_NEXT_REQUIRED { + values.insert(key, profile_value(snapshot, key, expected)?); } if values["qwen4exp.expert_used_count"] > values["qwen4exp.expert_count"] { return Err("runtime_profile: qwen4exp.expert_used_count exceeds qwen4exp.expert_count".into()); @@ -127,6 +104,35 @@ pub(super) fn validate_flash_next_profile(snapshot: &MetadataSnapshot) -> Result Ok(()) } +/// The integer keys of the runtime profile and the value each must have (`None`: any value in range). +const FLASH_NEXT_REQUIRED: [(&str, Option); 6] = [ + ("qwen4exp.block_count", Some(48)), + ("qwen4exp.embedding_length", Some(2560)), + ("qwen4exp.attention.head_count", Some(24)), + ("qwen4exp.attention.head_count_kv", Some(2)), + ("qwen4exp.expert_count", None), + ("qwen4exp.expert_used_count", None), +]; + +fn profile_value(snapshot: &MetadataSnapshot, key: &str, expected: Option) -> Result { + let not_u32 = |_| format!("runtime_profile: {key} must be a nonnegative 32-bit integer"); + let value = match snapshot.values.get(key) { + Some(MetadataValue::Unsigned(value)) => u32::try_from(*value).map_err(not_u32)?, + Some(MetadataValue::Signed(value)) => u32::try_from(*value).map_err(not_u32)?, + None => return Err(format!("runtime_profile: missing {key}").into()), + _ => return Err(format!("runtime_profile: {key} must be an integer").into()), + }; + if value == 0 || value > i32::MAX as u32 { + return Err(format!("runtime_profile: {key} must be in 1..2147483647").into()); + } + if let Some(expected) = expected + && value != expected + { + return Err(format!("runtime_profile: {key}={value}, expected {expected}").into()); + } + Ok(value) +} + /// Every metadata key/value of a GGUF file, in file order, bounded like the other readers (1M entries, 1 MiB /// strings, 1M-element arrays, 512 MiB of array text). Duplicate keys and nested arrays are refused, and so is a /// string that is not valid UTF-8 (`tools/gguf_reader.py` replaces bad bytes instead). Tensor payloads are never read. @@ -136,19 +142,11 @@ pub fn metadata_entries(path: &Path) -> Result> { read_index_file(&mut file, size, false)?; file.seek(SeekFrom::Start(0))?; let mut cursor = Cursor::new(&mut file, size); - cursor.skip(16)?; // magic, version, tensor count - let count = cursor.u64()?; - if count > 1_000_000 { - return Err("unreasonable GGUF header count".into()); - } + let count = cursor.metadata_count()?; let mut seen = HashSet::new(); let mut entries = Vec::new(); for _ in 0..count { - let key = cursor.string()?; - if !seen.insert(key.clone()) { - return Err(format!("duplicate GGUF metadata key: {key}").into()); - } - let kind = cursor.u32()?; + let (key, kind) = cursor.entry_header(&mut seen)?; entries.push((key, cursor.metadata_value(kind)?)); } Ok(entries) diff --git a/crates/model-format/src/gguf/read_index_file.rs b/crates/model-format/src/gguf/read_index_file.rs index 99061c66..b3423887 100644 --- a/crates/model-format/src/gguf/read_index_file.rs +++ b/crates/model-format/src/gguf/read_index_file.rs @@ -6,184 +6,59 @@ use super::*; pub(super) fn read_index_file(file: &mut File, size: u64, strict: bool) -> Result { file.seek(SeekFrom::Start(0))?; let mut cursor = Cursor::new(file, size); - if cursor.take(4)? != b"GGUF" { - return Err("not a GGUF file".into()); - } - if cursor.u32()? != 3 { - return Err("only GGUF v3 is supported".into()); - } - let tensors = cursor.u64()?; - let metadata = cursor.u64()?; - if tensors > 1_000_000 || metadata > 1_000_000 { - return Err("unreasonable GGUF header count".into()); - } - let mut architecture = None; - let mut split_no = None; - let mut split_count = None; - let mut split_tensors_count = None; - let mut alignment = 32u64; - let mut keys = HashSet::new(); - for _ in 0..metadata { - let key = cursor.string()?; - if !keys.insert(key.clone()) { - return Err(format!("duplicate GGUF metadata key: {key}").into()); - } - let kind = cursor.u32()?; - match (key.as_str(), kind) { - ("general.architecture", 8) => architecture = Some(cursor.string()?), - ("general.alignment", 4) => alignment = u64::from(cursor.u32()?), - ("general.alignment", _) => { - // tools/gguf_reader.py accepts any integer width; llama.cpp and the C++ engine read a uint32. - // Silently keeping the default would place the data section at the wrong byte. - return Err("general.alignment must be a uint32".into()); - } - ("split.no", 2) => split_no = Some(u64::from(cursor.u16()?)), - ("split.count", 2) => split_count = Some(u64::from(cursor.u16()?)), - ("split.tensors.count", 5) => { - let count = cursor.u32()?; - if count > i32::MAX as u32 { - return Err("negative GGUF split tensor count".into()); - } - split_tensors_count = Some(u64::from(count)); - } - ("split.no" | "split.count" | "split.tensors.count", _) => { - return Err("GGUF split metadata has an invalid integer type".into()); - } - _ => cursor.skip_value(kind)?, - } - } - if !alignment.is_power_of_two() || alignment > 4096 { - return Err("invalid GGUF alignment".into()); - } - let mut types = BTreeMap::new(); - let mut names = HashSet::new(); - let mut tensor_index = Vec::with_capacity(tensors as usize); - for _ in 0..tensors { - let name = cursor.string()?; - if !names.insert(name.clone()) { - return Err("duplicate GGUF tensor name".into()); - } - let dimensions = cursor.u32()?; - if !(1..=8).contains(&dimensions) { - return Err("invalid GGUF tensor dimensions".into()); - } - let mut shape = Vec::with_capacity(dimensions as usize); - for _ in 0..dimensions { - let dim = cursor.u64()?; - if dim == 0 { - return Err("zero GGUF tensor dimension".into()); - } - shape.push(dim); - } - let kind = cursor.u32()?; - let offset = cursor.u64()?; - *types.entry(kind).or_insert(0) += 1; - tensor_index.push(TensorInfo { name, dimensions: shape, kind, offset, bytes: 0 }); - } - let header_end = cursor.position()?; - let data_start = - header_end.checked_add(alignment - 1).ok_or("GGUF header offset overflow")? / alignment * alignment; - if data_start > size { - return Err("GGUF data section is truncated".into()); - } - for tensor in &tensor_index { - if tensor.offset % alignment != 0 || data_start.checked_add(tensor.offset).is_none_or(|start| start >= size) { - return Err("GGUF tensor offset is out of bounds or unaligned".into()); - } - } - if strict { - let mut positions = (0..tensor_index.len()).collect::>(); - if positions.is_empty() { - return Err("GGUF has no tensors to index".into()); - } - positions.sort_unstable_by_key(|&index| tensor_index[index].offset); - if tensor_index[positions[0]].offset != 0 { - return Err("GGUF first tensor does not start at data offset zero".into()); - } - for (at, &index) in positions.iter().enumerate() { - let tensor = &tensor_index[index]; - let (block_elements, block_bytes) = - block_geometry(tensor.kind).ok_or_else(|| format!("unsupported GGUF tensor type {}", tensor.kind))?; - let elements = tensor - .dimensions - .iter() - .try_fold(1u64, |product, dim| product.checked_mul(*dim)) - .ok_or("GGUF tensor element count overflow")?; - if tensor.dimensions[0] % block_elements != 0 { - return Err(format!("{}: tensor row is not block aligned", tensor.name).into()); - } - let bytes = elements - .checked_div(block_elements) - .and_then(|blocks| blocks.checked_mul(block_bytes)) - .ok_or("GGUF tensor byte count overflow")?; - let end = tensor.offset.checked_add(bytes).ok_or("GGUF tensor end overflow")?; - let next = positions.get(at + 1).map(|&next| tensor_index[next].offset).unwrap_or(size - data_start); - if end > next || next - end >= alignment { - return Err(format!("{}: tensor bytes overlap or have an invalid gap", tensor.name).into()); - } - tensor_index[index].bytes = bytes; - } - } - if let (Some(no), Some(count)) = (split_no, split_count) - && (count == 0 || no >= count) - { - return Err("invalid GGUF split metadata".into()); - } - let summary = Summary { - tensors, - metadata, - architecture, - split_no, - split_count, - split_tensors_count, - data_start, - file_size: size, - types, + let rules = IndexRules { + counts_ok: |tensors, metadata| tensors <= 1_000_000 && metadata <= 1_000_000, + reject_wide_alignment: true, }; - Ok(TensorIndex { summary, tensors: tensor_index }) + parse_index(&mut cursor, size, strict, &rules) } +/// (values per block, bytes per block) of each tensor kind. +/// +/// Mirrors engine/strata/include/strata/artifact/gguf_reader.hpp at the +/// upstream commit recorded in docs/upstream.md, plus the kinds +/// engine/strata/tools/gguf_reader.py BLOCK_GEOMETRY knows beyond it (Q8_K 15, +/// IQ1_S 19, F64 28, MXFP4 39, NVFP4 40). Geometry is only a byte count: a +/// consumer that cannot decode a kind still refuses it at use. Differential: +/// control-plane/tests/gguf_header_differential.rs. +const BLOCK_GEOMETRY: &[(u32, u64, u64)] = &[ + (0, 1, 4), + (1, 1, 2), + (30, 1, 2), + (2, 32, 18), + (3, 32, 20), + (6, 32, 22), + (7, 32, 24), + (8, 32, 34), + (9, 32, 36), + (10, 256, 84), + (11, 256, 110), + (21, 256, 110), + (12, 256, 144), + (13, 256, 176), + (14, 256, 210), + (15, 256, 292), + (16, 256, 66), + (17, 256, 74), + (18, 256, 98), + (19, 256, 50), + (20, 32, 18), + (22, 256, 82), + (23, 256, 136), + (24, 1, 1), + (28, 1, 8), + (29, 256, 56), + (39, 32, 17), + (40, 64, 36), + (42, 64, 18), + // APR trellis types (gguf_reader.hpp 143 to 146, gguf_reader.py BLOCK_GEOMETRY): 128 values per block, + // PTQ1_0 28 bytes, TQ2_T 34, TQK6 26, TQK7 30 + (143, 128, 28), + (144, 128, 34), + (145, 128, 26), + (146, 128, 30), +]; + pub fn block_geometry(kind: u32) -> Option<(u64, u64)> { - // Mirrors engine/strata/include/strata/artifact/gguf_reader.hpp at the - // upstream commit recorded in docs/upstream.md, plus the kinds - // engine/strata/tools/gguf_reader.py BLOCK_GEOMETRY knows beyond it (Q8_K 15, - // IQ1_S 19, F64 28, MXFP4 39, NVFP4 40). Geometry is only a byte count: a - // consumer that cannot decode a kind still refuses it at use. Differential: - // control-plane/tests/gguf_header_differential.rs. - Some(match kind { - 0 => (1, 4), - 1 | 30 => (1, 2), - 2 => (32, 18), - 3 => (32, 20), - 6 => (32, 22), - 7 => (32, 24), - 8 => (32, 34), - 9 => (32, 36), - 10 => (256, 84), - 11 | 21 => (256, 110), - 12 => (256, 144), - 13 => (256, 176), - 14 => (256, 210), - 15 => (256, 292), - 16 => (256, 66), - 17 => (256, 74), - 18 => (256, 98), - 19 => (256, 50), - 20 => (32, 18), - 22 => (256, 82), - 23 => (256, 136), - 24 => (1, 1), - 28 => (1, 8), - 29 => (256, 56), - 39 => (32, 17), - 40 => (64, 36), - 42 => (64, 18), - // APR trellis types (gguf_reader.hpp 143 to 146, gguf_reader.py BLOCK_GEOMETRY): 128 values per block, - // PTQ1_0 28 bytes, TQ2_T 34, TQK6 26, TQK7 30 - 143 => (128, 28), - 144 => (128, 34), - 145 => (128, 26), - 146 => (128, 30), - _ => return None, - }) + BLOCK_GEOMETRY.iter().find(|entry| entry.0 == kind).map(|entry| (entry.1, entry.2)) } diff --git a/crates/model-format/src/gguf/read_metadata_snapshot_with_architecture.rs b/crates/model-format/src/gguf/read_metadata_snapshot_with_architecture.rs index a0033cb7..9ec30506 100644 --- a/crates/model-format/src/gguf/read_metadata_snapshot_with_architecture.rs +++ b/crates/model-format/src/gguf/read_metadata_snapshot_with_architecture.rs @@ -1,8 +1,143 @@ -//! Moved out of the parent module by STRA-338: fn read_metadata_snapshot_with_architecture, fn validate_tokenizer_metadata, fn inspect, fn tensor_index, fn tensor_sha256, fn read_index. +//! Moved out of the parent module by STRA-338: fn read_metadata_snapshot_with_architecture, fn +//! validate_tokenizer_metadata, fn inspect, fn tensor_index, fn tensor_sha256, fn read_index. #[allow(unused_imports)] use super::*; +/// Which optional groups of keys a snapshot read keeps. +struct Wanted<'a> { + qwen_keys: Option<&'a [&'a str]>, + parse_tokenizer: bool, + parse_architecture: bool, +} + +/// The fields a snapshot read collects while it walks the metadata. +#[derive(Default)] +struct SnapshotBuilder { + architecture: Option, + split_no: Option, + split_count: Option, + split_tensors_count: Option, + model: Option, + pre: Option, + tokens: Option>, + merges: Option>, + token_types: Option>, + special_ids: BTreeMap, + chat_template: Option, + values: BTreeMap, +} + +impl SnapshotBuilder { + fn read_entry( + &mut self, + cursor: &mut Cursor, + key: String, + kind: u32, + want: &Wanted, + ) -> Result<()> { + if self.try_architecture(cursor, &key, kind, want)? || self.try_split(cursor, &key, kind)? { + return Ok(()); + } + if want.parse_tokenizer && self.try_tokenizer(cursor, &key, kind)? { + return Ok(()); + } + if want.qwen_keys.is_some_and(|keys| keys.contains(&key.as_str())) { + self.values.insert(key, cursor.metadata_value(kind)?); + return Ok(()); + } + cursor.skip_value(kind) + } + + fn try_architecture( + &mut self, + cursor: &mut Cursor, + key: &str, + kind: u32, + want: &Wanted, + ) -> Result { + if key != "general.architecture" || !want.parse_architecture || kind != 8 { + return Ok(false); + } + self.architecture = Some(cursor.string()?); + Ok(true) + } + + fn try_split(&mut self, cursor: &mut Cursor, key: &str, kind: u32) -> Result { + match (key, kind) { + ("split.no", 2) => self.split_no = Some(u64::from(cursor.u16()?)), + ("split.count", 2) => self.split_count = Some(u64::from(cursor.u16()?)), + ("split.tensors.count", 5) => self.split_tensors_count = Some(u64::from(cursor.u32()?)), + ("split.no" | "split.count" | "split.tensors.count", _) => { + return Err("GGUF split metadata has an invalid integer type".into()); + } + _ => return Ok(false), + } + Ok(true) + } + + fn try_tokenizer(&mut self, cursor: &mut Cursor, key: &str, kind: u32) -> Result { + Ok(self.try_text(cursor, key, kind)? + || self.try_arrays(cursor, key, kind)? + || self.try_special_id(cursor, key, kind)?) + } + + fn try_text(&mut self, cursor: &mut Cursor, key: &str, kind: u32) -> Result { + let slot = match key { + "tokenizer.ggml.model" => &mut self.model, + "tokenizer.ggml.pre" => &mut self.pre, + "tokenizer.chat_template" => &mut self.chat_template, + _ => return Ok(false), + }; + if kind != 8 { + return Ok(false); + } + *slot = Some(cursor.string()?); + Ok(true) + } + + fn try_arrays(&mut self, cursor: &mut Cursor, key: &str, kind: u32) -> Result { + match key { + "tokenizer.ggml.tokens" => self.tokens = Some(cursor.string_array(kind)?), + "tokenizer.ggml.merges" => self.merges = Some(cursor.string_array(kind)?), + "tokenizer.ggml.token_type" => self.token_types = Some(cursor.integer_array(kind)?), + _ => return Ok(false), + } + Ok(true) + } + + fn try_special_id(&mut self, cursor: &mut Cursor, key: &str, kind: u32) -> Result { + if !key.starts_with("tokenizer.ggml.") || !key.ends_with("_token_id") { + return Ok(false); + } + self.special_ids.insert(key.to_owned(), cursor.integer(kind)?); + Ok(true) + } + + fn finish(self) -> MetadataSnapshot { + let tokenizer = match (self.model, self.tokens, self.merges, self.chat_template) { + (Some(model), Some(tokens), Some(merges), Some(chat_template)) => Some(TokenizerMetadata { + model, + pre: self.pre.unwrap_or_else(|| "qwen35".to_owned()), + tokens, + merges, + token_types: self.token_types, + special_ids: self.special_ids, + chat_template, + }), + _ => None, + }; + MetadataSnapshot { + architecture: self.architecture, + split_no: self.split_no, + split_count: self.split_count, + split_tensors_count: self.split_tensors_count, + values: self.values, + tokenizer, + } + } +} + pub(super) fn read_metadata_snapshot_with_architecture( file: &mut File, size: u64, @@ -12,85 +147,46 @@ pub(super) fn read_metadata_snapshot_with_architecture( ) -> Result { file.seek(SeekFrom::Start(0))?; let mut cursor = Cursor::new(file, size); - cursor.skip(16)?; // magic, version, tensor count - let count = cursor.u64()?; - if count > 1_000_000 { - return Err("unreasonable GGUF header count".into()); - } - let mut architecture = None; - let mut split_no = None; - let mut split_count = None; - let mut split_tensors_count = None; - let mut model = None; - let mut pre = None; - let mut tokens = None; - let mut merges = None; - let mut token_types = None; - let mut special_ids = BTreeMap::new(); - let mut chat_template = None; - let mut values = BTreeMap::new(); + let count = cursor.metadata_count()?; + let want = Wanted { qwen_keys, parse_tokenizer, parse_architecture }; + let mut builder = SnapshotBuilder::default(); let mut seen = HashSet::new(); for _ in 0..count { - let key = cursor.string()?; - if !seen.insert(key.clone()) { - return Err(format!("duplicate GGUF metadata key: {key}").into()); - } - let kind = cursor.u32()?; - match key.as_str() { - "general.architecture" if parse_architecture && kind == 8 => architecture = Some(cursor.string()?), - "split.no" if kind == 2 => split_no = Some(u64::from(cursor.u16()?)), - "split.count" if kind == 2 => split_count = Some(u64::from(cursor.u16()?)), - "split.tensors.count" if kind == 5 => split_tensors_count = Some(u64::from(cursor.u32()?)), - "split.no" | "split.count" | "split.tensors.count" => { - return Err("GGUF split metadata has an invalid integer type".into()); - } - "tokenizer.ggml.model" if parse_tokenizer && kind == 8 => model = Some(cursor.string()?), - "tokenizer.ggml.pre" if parse_tokenizer && kind == 8 => pre = Some(cursor.string()?), - "tokenizer.ggml.tokens" if parse_tokenizer => tokens = Some(cursor.string_array(kind)?), - "tokenizer.ggml.merges" if parse_tokenizer => merges = Some(cursor.string_array(kind)?), - "tokenizer.ggml.token_type" if parse_tokenizer => token_types = Some(cursor.integer_array(kind)?), - "tokenizer.chat_template" if parse_tokenizer && kind == 8 => chat_template = Some(cursor.string()?), - _ if parse_tokenizer && key.starts_with("tokenizer.ggml.") && key.ends_with("_token_id") => { - special_ids.insert(key, cursor.integer(kind)?); - } - _ if qwen_keys.is_some_and(|keys| keys.contains(&key.as_str())) => { - values.insert(key, cursor.metadata_value(kind)?); - } - _ => cursor.skip_value(kind)?, - } + let (key, kind) = cursor.entry_header(&mut seen)?; + builder.read_entry(&mut cursor, key, kind, &want)?; } - let tokenizer = match (model, tokens, merges, chat_template) { - (Some(model), Some(tokens), Some(merges), Some(chat_template)) => Some(TokenizerMetadata { - model, - pre: pre.unwrap_or_else(|| "qwen35".to_owned()), - tokens, - merges, - token_types, - special_ids, - chat_template, - }), - _ => None, - }; - Ok(MetadataSnapshot { architecture, split_no, split_count, split_tensors_count, values, tokenizer }) + Ok(builder.finish()) } pub(crate) fn validate_tokenizer_metadata(tokenizer: TokenizerMetadata) -> Result { - let TokenizerMetadata { model, pre, tokens, merges, token_types, special_ids, chat_template } = tokenizer; - if model != "gpt2" || pre != "qwen35" { - return Err("only the qwen35 byte-level BPE tokenizer is supported".into()); - } - if tokens.is_empty() || chat_template.is_empty() { - return Err("GGUF tokenizer has an empty vocabulary or chat template".into()); - } - if token_types.as_ref().is_some_and(|types| types.len() != tokens.len()) { - return Err("token_type length differs from vocabulary length".into()); - } - let vocab: HashSet<&str> = tokens.iter().map(String::as_str).collect(); - if vocab.len() != tokens.len() { + check_tokenizer_shape(&tokenizer)?; + let vocab: HashSet<&str> = tokenizer.tokens.iter().map(String::as_str).collect(); + if vocab.len() != tokenizer.tokens.len() { return Err("GGUF tokenizer has duplicate vocabulary entries".into()); } + check_merges(&tokenizer.merges, &vocab)?; + if tokenizer.special_ids.values().any(|&id| id as usize >= tokenizer.tokens.len()) { + return Err("special token ID exceeds vocabulary".into()); + } + Ok(tokenizer) +} + +fn check_tokenizer_shape(tokenizer: &TokenizerMetadata) -> Result<()> { + if tokenizer.model != "gpt2" || tokenizer.pre != "qwen35" { + return Err("only the qwen35 byte-level BPE tokenizer is supported".into()); + } + if tokenizer.tokens.is_empty() || tokenizer.chat_template.is_empty() { + return Err("GGUF tokenizer has an empty vocabulary or chat template".into()); + } + if tokenizer.token_types.as_ref().is_some_and(|types| types.len() != tokenizer.tokens.len()) { + return Err("token_type length differs from vocabulary length".into()); + } + Ok(()) +} + +fn check_merges(merges: &[String], vocab: &HashSet<&str>) -> Result<()> { let mut seen_merges = HashSet::new(); - for merge in &merges { + for merge in merges { let Some((left, right)) = merge.split_once(' ') else { return Err("GGUF BPE merge is not a pair".into()); }; @@ -104,12 +200,7 @@ pub(crate) fn validate_tokenizer_metadata(tokenizer: TokenizerMetadata) -> Resul return Err("GGUF BPE merge is invalid or duplicated".into()); } } - for &id in special_ids.values() { - if id as usize >= tokens.len() { - return Err("special token ID exceeds vocabulary".into()); - } - } - Ok(TokenizerMetadata { model, pre, tokens, merges, token_types, special_ids, chat_template }) + Ok(()) } pub fn inspect(path: &Path) -> Result { @@ -134,13 +225,16 @@ pub fn tensor_sha256(path: &Path, index: &TensorIndex, tensor_number: usize) -> return Err("GGUF tensor exceeds indexed file".into()); } let mut file = File::open(path)?; - if file.metadata()?.len() != index.summary.file_size { - return Err("GGUF source size changed after indexing".into()); - } + ensure_size(&file, index.summary.file_size, "GGUF source size changed after indexing")?; + hash_span(&mut file, absolute, tensor.bytes) +} + +/// SHA-256 of `bytes` bytes at `absolute`, read through a 1 MiB buffer. +fn hash_span(file: &mut File, absolute: u64, bytes: u64) -> Result<[u8; 32]> { file.seek(SeekFrom::Start(absolute))?; let mut digest = Sha256::new(); let mut buffer = vec![0u8; 1024 * 1024]; - let mut remaining = tensor.bytes; + let mut remaining = bytes; while remaining > 0 { let count = remaining.min(buffer.len() as u64) as usize; file.read_exact(&mut buffer[..count])?; diff --git a/crates/model-format/src/gguf/stream_buffer_bytes.rs b/crates/model-format/src/gguf/stream_buffer_bytes.rs index a9aab2e9..6d51dd91 100644 --- a/crates/model-format/src/gguf/stream_buffer_bytes.rs +++ b/crates/model-format/src/gguf/stream_buffer_bytes.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: fn stream_buffer_bytes, fn stream_buffer_bytes, fn with_test_stream_buffer. +//! Moved out of the parent module by STRA-338: fn stream_buffer_bytes, fn stream_buffer_bytes, fn +//! with_test_stream_buffer. #[allow(unused_imports)] use super::*; diff --git a/crates/model-format/src/gguf/tests/admits_flash_metadata_and_rejects.rs b/crates/model-format/src/gguf/tests/admits_flash_metadata_and_rejects.rs index 80fbe356..b9b8c4c4 100644 --- a/crates/model-format/src/gguf/tests/admits_flash_metadata_and_rejects.rs +++ b/crates/model-format/src/gguf/tests/admits_flash_metadata_and_rejects.rs @@ -1,4 +1,7 @@ -//! Tests of tests by topic (moved out of the test file by STRA-338): admits_flash_metadata_and_rejects_incompatible_profiles, inspects_header_and_rejects_truncated_payload, indexes_exact_mixed_tensor_spans_and_rejects_bad_layouts, owned_handle_verifies_artifact_and_streams_exact_tensor_bytes_with_bounded_chunks .... +//! Tests of tests by topic (moved out of the test file by STRA-338): +//! admits_flash_metadata_and_rejects_incompatible_profiles, inspects_header_and_rejects_truncated_payload, +//! indexes_exact_mixed_tensor_spans_and_rejects_bad_layouts, +//! owned_handle_verifies_artifact_and_streams_exact_tensor_bytes_with_bounded_chunks .... #[allow(unused_imports)] use super::*; diff --git a/crates/model-format/src/gguf/tests/buffered_cursor_preserves_offsets_parsin.rs b/crates/model-format/src/gguf/tests/buffered_cursor_preserves_offsets_parsin.rs index 65201e42..ef78c933 100644 --- a/crates/model-format/src/gguf/tests/buffered_cursor_preserves_offsets_parsin.rs +++ b/crates/model-format/src/gguf/tests/buffered_cursor_preserves_offsets_parsin.rs @@ -1,4 +1,5 @@ -//! Tests of tests by topic (moved out of the test file by STRA-338): buffered_cursor_preserves_offsets_parsing_and_refusals_with_bounded_reads. +//! Tests of tests by topic (moved out of the test file by STRA-338): +//! buffered_cursor_preserves_offsets_parsing_and_refusals_with_bounded_reads. #[allow(unused_imports)] use super::*; diff --git a/crates/model-format/src/gguf/tests/empty_owned_tensor_validation_preserves.rs b/crates/model-format/src/gguf/tests/empty_owned_tensor_validation_preserves.rs index 5b487d91..127466c1 100644 --- a/crates/model-format/src/gguf/tests/empty_owned_tensor_validation_preserves.rs +++ b/crates/model-format/src/gguf/tests/empty_owned_tensor_validation_preserves.rs @@ -1,4 +1,8 @@ -//! Tests of tests by topic (moved out of the test file by STRA-338): empty_owned_tensor_validation_preserves_cursor_bounds_and_size_checks, owned_tensor_bounds_are_checked_before_any_callback_and_stream_can_recover, pathname_replacement_keeps_original_verified_file_and_index, opened_file_size_changes_are_refused_and_same_size_mutation_is_not_immutability. +//! Tests of tests by topic (moved out of the test file by STRA-338): +//! empty_owned_tensor_validation_preserves_cursor_bounds_and_size_checks, +//! owned_tensor_bounds_are_checked_before_any_callback_and_stream_can_recover, +//! pathname_replacement_keeps_original_verified_file_and_index, +//! opened_file_size_changes_are_refused_and_same_size_mutation_is_not_immutability. #[allow(unused_imports)] use super::*; diff --git a/crates/model-format/src/gguf/tests/original_first_source_fence_retains.rs b/crates/model-format/src/gguf/tests/original_first_source_fence_retains.rs index 069e4be5..15312305 100644 --- a/crates/model-format/src/gguf/tests/original_first_source_fence_retains.rs +++ b/crates/model-format/src/gguf/tests/original_first_source_fence_retains.rs @@ -1,4 +1,5 @@ -//! Tests of tests by topic (moved out of the test file by STRA-338): original_first_source_fence_retains_opened_fd_cursor_and_refuses_length_changes. +//! Tests of tests by topic (moved out of the test file by STRA-338): +//! original_first_source_fence_retains_opened_fd_cursor_and_refuses_length_changes. #[allow(unused_imports)] use super::*; diff --git a/crates/model-format/src/gguf_digest_capture.rs b/crates/model-format/src/gguf_digest_capture.rs index 8532ebbc..4e982b45 100644 --- a/crates/model-format/src/gguf_digest_capture.rs +++ b/crates/model-format/src/gguf_digest_capture.rs @@ -16,14 +16,7 @@ fn open_with_capture( prepare: impl FnOnce(&TensorIndex) -> ProvisionalExpertSource, ) -> Result<(VerifiedGgufFile, ProvisionalExpertSource)> { let expected_digest = parse_artifact_digest(expected_digest)?; - if !std::fs::metadata(path)?.is_file() { - return Err("GGUF source must be a regular file".into()); - } - let mut file = File::open(path)?; - let metadata = file.metadata()?; - if !metadata.is_file() { - return Err("GGUF source must be a regular file".into()); - } + let (mut file, metadata) = open_regular_file(path)?; let size = metadata.len(); // Provisional parsing grants no source authority. Its failure is deferred, // and the original strict index is parsed independently AFTER full SHA. @@ -31,28 +24,29 @@ fn open_with_capture( Ok(index) => prepare(&index), Err(_) => ProvisionalExpertSource::geometry_failure(), }; + let actual_digest = digest_observed(&mut file, size, &mut capture)?; + if actual_digest != expected_digest { + return Err("GGUF artifact SHA256 mismatch".into()); + } + ensure_size(&file, size, "GGUF source size changed during verification")?; + let index = read_index_file(&mut file, size, true)?; + ensure_size(&file, size, "GGUF source size changed during indexing")?; + let mut verified = VerifiedGgufFile { file, index, artifact_sha256: actual_digest, resident_source_id: None }; + capture.bind_verified(&mut verified); + Ok((verified, capture)) +} + +/// SHA-256 of the whole file, streamed once; the capture sees every chunk at its file position. +fn digest_observed(file: &mut File, size: u64, capture: &mut ProvisionalExpertSource) -> Result<[u8; 32]> { let mut digest = Sha256::new(); let mut position = 0u64; - stream_file_span(&mut file, 0, size, |chunk| { + stream_file_span(file, 0, size, |chunk| { digest.update(chunk); capture.observe(position, chunk); position += chunk.len() as u64; // bounded by the unchanged stream span Ok(()) })?; - let actual_digest: [u8; 32] = digest.finalize().into(); - if actual_digest != expected_digest { - return Err("GGUF artifact SHA256 mismatch".into()); - } - if file.metadata()?.len() != size { - return Err("GGUF source size changed during verification".into()); - } - let index = read_index_file(&mut file, size, true)?; - if file.metadata()?.len() != size { - return Err("GGUF source size changed during indexing".into()); - } - let mut verified = VerifiedGgufFile { file, index, artifact_sha256: actual_digest, resident_source_id: None }; - capture.bind_verified(&mut verified); - Ok((verified, capture)) + Ok(digest.finalize().into()) } // Bounded provisional header parse only; final authority remains the untouched @@ -60,136 +54,11 @@ fn open_with_capture( fn read_provisional_index(file: &mut File, size: u64, strict: bool) -> Result { file.seek(SeekFrom::Start(0))?; let mut cursor = Cursor::new(file, size.min(64 * 1024 * 1024)); - if cursor.take(4)? != b"GGUF" { - return Err("not a GGUF file".into()); - } - if cursor.u32()? != 3 { - return Err("only GGUF v3 is supported".into()); - } - let tensors = cursor.u64()?; - let metadata = cursor.u64()?; - if tensors != 1223 || metadata > 65_536 { - return Err("unreasonable GGUF header count".into()); - } - let mut architecture = None; - let mut split_no = None; - let mut split_count = None; - let mut split_tensors_count = None; - let mut alignment = 32u64; - let mut keys = HashSet::new(); - for _ in 0..metadata { - let key = cursor.string()?; - if !keys.insert(key.clone()) { - return Err(format!("duplicate GGUF metadata key: {key}").into()); - } - let kind = cursor.u32()?; - match (key.as_str(), kind) { - ("general.architecture", 8) => architecture = Some(cursor.string()?), - ("general.alignment", 4) => alignment = u64::from(cursor.u32()?), - ("split.no", 2) => split_no = Some(u64::from(cursor.u16()?)), - ("split.count", 2) => split_count = Some(u64::from(cursor.u16()?)), - ("split.tensors.count", 5) => { - let count = cursor.u32()?; - if count > i32::MAX as u32 { - return Err("negative GGUF split tensor count".into()); - } - split_tensors_count = Some(u64::from(count)); - } - ("split.no" | "split.count" | "split.tensors.count", _) => { - return Err("GGUF split metadata has an invalid integer type".into()); - } - _ => cursor.skip_value(kind)?, - } - } - if !alignment.is_power_of_two() || alignment > 4096 { - return Err("invalid GGUF alignment".into()); - } - let mut types = BTreeMap::new(); - let mut names = HashSet::new(); - let mut tensor_index = Vec::with_capacity(tensors as usize); - for _ in 0..tensors { - let name = cursor.string()?; - if !names.insert(name.clone()) { - return Err("duplicate GGUF tensor name".into()); - } - let dimensions = cursor.u32()?; - if !(1..=8).contains(&dimensions) { - return Err("invalid GGUF tensor dimensions".into()); - } - let mut shape = Vec::with_capacity(dimensions as usize); - for _ in 0..dimensions { - let dim = cursor.u64()?; - if dim == 0 { - return Err("zero GGUF tensor dimension".into()); - } - shape.push(dim); - } - let kind = cursor.u32()?; - let offset = cursor.u64()?; - *types.entry(kind).or_insert(0) += 1; - tensor_index.push(TensorInfo { name, dimensions: shape, kind, offset, bytes: 0 }); - } - let header_end = cursor.position()?; - let data_start = - header_end.checked_add(alignment - 1).ok_or("GGUF header offset overflow")? / alignment * alignment; - if data_start > size { - return Err("GGUF data section is truncated".into()); - } - for tensor in &tensor_index { - if tensor.offset % alignment != 0 || data_start.checked_add(tensor.offset).is_none_or(|start| start >= size) { - return Err("GGUF tensor offset is out of bounds or unaligned".into()); - } - } - if strict { - let mut positions = (0..tensor_index.len()).collect::>(); - if positions.is_empty() { - return Err("GGUF has no tensors to index".into()); - } - positions.sort_unstable_by_key(|&index| tensor_index[index].offset); - if tensor_index[positions[0]].offset != 0 { - return Err("GGUF first tensor does not start at data offset zero".into()); - } - for (at, &index) in positions.iter().enumerate() { - let tensor = &tensor_index[index]; - let (block_elements, block_bytes) = - block_geometry(tensor.kind).ok_or_else(|| format!("unsupported GGUF tensor type {}", tensor.kind))?; - let elements = tensor - .dimensions - .iter() - .try_fold(1u64, |product, dim| product.checked_mul(*dim)) - .ok_or("GGUF tensor element count overflow")?; - if tensor.dimensions[0] % block_elements != 0 { - return Err(format!("{}: tensor row is not block aligned", tensor.name).into()); - } - let bytes = elements - .checked_div(block_elements) - .and_then(|blocks| blocks.checked_mul(block_bytes)) - .ok_or("GGUF tensor byte count overflow")?; - let end = tensor.offset.checked_add(bytes).ok_or("GGUF tensor end overflow")?; - let next = positions.get(at + 1).map(|&next| tensor_index[next].offset).unwrap_or(size - data_start); - if end > next || next - end >= alignment { - return Err(format!("{}: tensor bytes overlap or have an invalid gap", tensor.name).into()); - } - tensor_index[index].bytes = bytes; - } - } - if let (Some(no), Some(count)) = (split_no, split_count) - && (count == 0 || no >= count) - { - return Err("invalid GGUF split metadata".into()); - } - let summary = Summary { - tensors, - metadata, - architecture, - split_no, - split_count, - split_tensors_count, - data_start, - file_size: size, - types, + let rules = IndexRules { + counts_ok: |tensors, metadata| tensors == 1223 && metadata <= 65_536, + reject_wide_alignment: false, }; - Ok(TensorIndex { summary, tensors: tensor_index }) + parse_index(&mut cursor, size, strict, &rules) } #[cfg(test)] diff --git a/crates/model-format/src/gguf_digest_capture_sdet.rs b/crates/model-format/src/gguf_digest_capture_sdet.rs index f17e77f7..08be40bb 100644 --- a/crates/model-format/src/gguf_digest_capture_sdet.rs +++ b/crates/model-format/src/gguf_digest_capture_sdet.rs @@ -50,6 +50,25 @@ fn original_stream_first_digest_capture_bytes_priority_coverage_and_source_owner let fixture = Fixture::new(); // ORIGINAL whole digest/index and old tensor stream FIRST, with real FD. let mut original = VerifiedGgufFile::open(&fixture.path, &fixture.digest()).unwrap(); + let expected = stream_whole_tensor(&mut original); + let index = read_index_file(&mut original.file, fixture.bytes.len() as u64, true).unwrap(); + let resident = mint_from_stream(&fixture, &mut original, &index, &expected); + let foreign = VerifiedGgufFile::open(&fixture.path, &fixture.digest()).unwrap(); + assert!(foreign.copy_resident_tensor(&resident, 0, vec![0; 64].into_boxed_slice()).is_err()); + check_chunk_widths(&fixture, &index, &expected); + check_incomplete_captures(&fixture, &index, &mut original); + let (new, deferred) = check_open_precedence(&fixture, &original); + check_replaced_path(&fixture, &mut original, &resident, &expected); + drop(resident); + drop(foreign); + drop(original); + drop(new); + drop(deferred); + drop(fixture); + check_admission_boundaries(); +} + +fn stream_whole_tensor(original: &mut VerifiedGgufFile) -> Vec { let mut expected = Vec::new(); original .stream_tensor(0, 0, 64, |part| { @@ -57,8 +76,17 @@ fn original_stream_first_digest_capture_bytes_priority_coverage_and_source_owner Ok(()) }) .unwrap(); - let index = read_index_file(&mut original.file, fixture.bytes.len() as u64, true).unwrap(); - let mut candidate = ProvisionalExpertSource::test_cells(&index); + expected +} + +/// The capture observes the whole-file digest stream; its bytes are the old stream's, and it mints a resident tensor. +fn mint_from_stream( + fixture: &Fixture, + original: &mut VerifiedGgufFile, + index: &TensorIndex, + expected: &[u8], +) -> ResidentTensor { + let mut candidate = ProvisionalExpertSource::test_cells(index); let mut digest = Sha256::new(); let mut position = 0; stream_file_span(&mut original.file, 0, fixture.bytes.len() as u64, |part| { @@ -70,44 +98,56 @@ fn original_stream_first_digest_capture_bytes_priority_coverage_and_source_owner .unwrap(); assert_eq!(format!("sha256:{}", hex(&digest.finalize())), fixture.digest()); assert_eq!(candidate.test_bytes().unwrap(), expected); - let resident = candidate.test_mint(&mut original).unwrap(); + let resident = candidate.test_mint(original).unwrap(); let out = original.copy_resident_tensor(&resident, 3, vec![0; 17].into_boxed_slice()).unwrap(); assert_eq!(&*out, &expected[3..20]); - let foreign = VerifiedGgufFile::open(&fixture.path, &fixture.digest()).unwrap(); - assert!(foreign.copy_resident_tensor(&resident, 0, vec![0; 64].into_boxed_slice()).is_err()); - // Independent chunk sizes exercise exact overlaps, prefix/tail and zero - // chunks. These private fixture cells cannot publish a Qwen model bank. + resident +} + +/// Independent chunk sizes exercise exact overlaps, prefix/tail and zero +/// chunks. These private fixture cells cannot publish a Qwen model bank. +fn check_chunk_widths(fixture: &Fixture, index: &TensorIndex, expected: &[u8]) { for width in 1..=fixture.bytes.len() + 1 { - let mut capture = ProvisionalExpertSource::test_cells(&index); + let mut capture = ProvisionalExpertSource::test_cells(index); capture.observe(0, &[]); for (number, part) in fixture.bytes.chunks(width).enumerate() { capture.observe((number * width) as u64, part); } assert_eq!(capture.test_bytes().unwrap(), expected); } +} + +/// A stream that skips the start of the tensor, or replays it, discards the capture. +fn check_incomplete_captures(fixture: &Fixture, index: &TensorIndex, original: &mut VerifiedGgufFile) { let start = index.summary.data_start; - let mut missing = ProvisionalExpertSource::test_cells(&index); + let mut missing = ProvisionalExpertSource::test_cells(index); missing.observe(start + 1, &fixture.bytes[start as usize + 1..]); assert!(missing.test_discarded()); - assert!(missing.test_mint(&mut original).is_err()); - let mut replay = ProvisionalExpertSource::test_cells(&index); + assert!(missing.test_mint(original).is_err()); + let mut replay = ProvisionalExpertSource::test_cells(index); replay.observe(0, &fixture.bytes); replay.observe(start, &fixture.bytes[start as usize..]); assert!(replay.test_discarded()); - // Optional real open on a tiny non-Qwen file still verifies SHA/index. Its - // closed144 plan refuses privately; neither invalid KAR nor plan error is - // surfaced before the original gates. No 50GB allocation in this fixture. +} + +/// Optional real open on a tiny non-Qwen file still verifies SHA/index. Its +/// closed144 plan refuses privately; neither invalid KAR nor plan error is +/// surfaced before the original gates. No 50GB allocation in this fixture. +fn check_open_precedence( + fixture: &Fixture, + original: &VerifiedGgufFile, +) -> (VerifiedGgufFile, ProvisionalExpertSource) { let (new, deferred) = open_expert_capture(&fixture.path, &fixture.digest(), None).unwrap(); assert!(deferred.test_discarded()); assert_eq!(new.artifact_sha256(), original.artifact_sha256()); assert_eq!(new.index().summary.file_size, original.index().summary.file_size); let wrong = format!("sha256:{}", "0".repeat(64)); let old = VerifiedGgufFile::open(&fixture.path, &wrong).unwrap_err().to_string(); - let new = match open_expert_capture(&fixture.path, &wrong, None) { + let refused = match open_expert_capture(&fixture.path, &wrong, None) { Err(error) => error.to_string(), Ok(_) => panic!("wrong digest must fail"), }; - assert_eq!(old, new); + assert_eq!(old, refused); // Correct hash of malformed index: same original index failure wins, even // though provisional parse and observational budget already refused. let mut malformed = fixture.bytes.clone(); @@ -116,26 +156,26 @@ fn original_stream_first_digest_capture_bytes_priority_coverage_and_source_owner std::fs::write(&malformed_path, &malformed).unwrap(); let actual_digest = format!("sha256:{}", hex(&Sha256::digest(&malformed))); let old = VerifiedGgufFile::open(&malformed_path, &actual_digest).unwrap_err().to_string(); - let new = match open_expert_capture(&malformed_path, &actual_digest, None) { + let refused = match open_expert_capture(&malformed_path, &actual_digest, None) { Err(error) => error.to_string(), Ok(_) => panic!("bad index must fail"), }; - assert_eq!(old, new); - // Path replacement never replaces the actual verified descriptor. Current - // opened-file size change still refuses existing resident copies. + assert_eq!(old, refused); + (new, deferred) +} + +/// Path replacement never replaces the actual verified descriptor. Current +/// opened-file size change still refuses existing resident copies. +fn check_replaced_path(fixture: &Fixture, original: &mut VerifiedGgufFile, resident: &ResidentTensor, expected: &[u8]) { let retained = fixture.directory.join("retained.gguf"); std::fs::rename(&fixture.path, &retained).unwrap(); std::fs::write(&fixture.path, b"unrelated path").unwrap(); - assert_eq!(&*original.copy_resident_tensor(&resident, 0, vec![0; 64].into_boxed_slice()).unwrap(), expected); + assert_eq!(&*original.copy_resident_tensor(resident, 0, vec![0; 64].into_boxed_slice()).unwrap(), expected); std::fs::OpenOptions::new().write(true).open(&retained).unwrap().set_len(1).unwrap(); - assert!(original.copy_resident_tensor(&resident, 0, vec![0; 64].into_boxed_slice()).is_err()); - drop(resident); - drop(foreign); - drop(original); - drop(new); - drop(deferred); - drop(fixture); + assert!(original.copy_resident_tensor(resident, 0, vec![0; 64].into_boxed_slice()).is_err()); +} +fn check_admission_boundaries() { let admit = ProvisionalExpertSource::test_memory; let cap = 52usize * 1024 * 1024 * 1024; let headroom = 8usize * 1024 * 1024 * 1024; diff --git a/crates/model-format/src/gguf_native_head.rs b/crates/model-format/src/gguf_native_head.rs index 15731624..98da7434 100644 --- a/crates/model-format/src/gguf_native_head.rs +++ b/crates/model-format/src/gguf_native_head.rs @@ -1,6 +1,9 @@ //! Literal Original GgufModel head/embedding admission over genuinely verified FDs. //! Child of gguf; snapshots parse the SAME FD, never an asserted host certificate. -use super::{FLASH_NEXT_PROFILE_KEYS, MetadataValue, Result, VerifiedGgufFile, read_metadata_snapshot}; +use super::{ + FLASH_NEXT_PROFILE_KEYS, MetadataSnapshot, MetadataValue, Result, Summary, TensorIndex, VerifiedGgufFile, + read_metadata_snapshot, +}; use std::{collections::BTreeMap, path::Path}; pub struct NativeHeadGgufModel { shards: Vec, @@ -35,31 +38,46 @@ impl NativeHeadTensor { &self.bytes } } +/// (kind, values per block, bytes per block) of the tensor kinds a head or an embedding may use. +const ROW_GEOMETRY: [(u32, usize, usize); 17] = [ + (2, 32, 18), + (20, 32, 18), + (6, 32, 22), + (7, 32, 24), + (8, 32, 34), + (11, 256, 110), + (21, 256, 110), + (12, 256, 144), + (13, 256, 176), + (14, 256, 210), + (16, 256, 66), + (17, 256, 74), + (18, 256, 98), + (22, 256, 82), + (23, 256, 136), + (29, 256, 56), + (42, 64, 18), +]; fn row_bytes(kind: u32, n: usize) -> Option { - let (b, k) = match kind { - 2 | 20 => (32, 18), - 6 => (32, 22), - 7 => (32, 24), - 8 => (32, 34), - 11 | 21 => (256, 110), - 12 => (256, 144), - 13 => (256, 176), - 14 => (256, 210), - 16 => (256, 66), - 17 => (256, 74), - 18 => (256, 98), - 22 => (256, 82), - 23 => (256, 136), - 29 => (256, 56), - 42 => (64, 18), - 30 => (1, 2), - _ => return None, + let (b, k) = match ROW_GEOMETRY.iter().find(|entry| entry.0 == kind) { + Some(&(_, b, k)) => (b, k), + None if kind == 30 => (1, 2), + None => return None, }; if !n.is_multiple_of(b) { return None; } (n / b).checked_mul(k) } +/// The dimension keys of the head profile and the value each must have (0: any value). +const HEAD_PROFILE: [(&str, u64); 6] = [ + ("qwen4exp.block_count", 48), + ("qwen4exp.embedding_length", 2560), + ("qwen4exp.expert_count", 0), + ("qwen4exp.expert_used_count", 0), + ("qwen4exp.attention.head_count", 24), + ("qwen4exp.attention.head_count_kv", 2), +]; impl NativeHeadGgufModel { pub fn open(paths: &[(&Path, &str)], embedding_override: bool) -> Result { let mut shards = Vec::new(); @@ -72,43 +90,8 @@ impl NativeHeadGgufModel { /// Original split/order/duplicate/architecture admission, preserving the real /// source/index pair. Existing verified owners avoid an additional digest pass. pub fn from_verified(mut shards: Vec, embedding_override: bool) -> Result { - if shards.is_empty() { - return Err("GGUF model has no shards".into()); - } - let n = shards.len(); - let first = &shards[0].index.summary; - if n == 1 { - if first.split_count.is_some_and(|count| count > 1) { - return Err("GGUF split model opened as a whole model".into()); - } - } else { - if first.architecture.is_none() { - return Err("GGUF first shard has no general.architecture".into()); - } - let total = first.split_tensors_count; - let mut count = 0u64; - for (i, g) in shards.iter().enumerate() { - let s = &g.index.summary; - if s.split_count != Some(n as u64) - || s.split_no != Some(i as u64) - || total.is_some() && s.split_tensors_count != total - { - return Err("GGUF split metadata/order mismatch".into()); - } - count = count.checked_add(g.index.tensors.len() as u64).ok_or("GGUF tensor count overflow")?; - } - if total.is_some_and(|total| total != count) { - return Err("GGUF split tensor count mismatch".into()); - } - } - let mut names = BTreeMap::new(); - for (s, g) in shards.iter().enumerate() { - for (i, t) in g.index.tensors.iter().enumerate() { - if names.insert(t.name.clone(), (s, i)).is_some() { - return Err("GGUF duplicate tensor across shards".into()); - } - } - } + check_shard_order(&shards)?; + let names = index_names(&shards)?; let g = &mut shards[0]; g.check_size()?; let snapshot = @@ -116,26 +99,7 @@ impl NativeHeadGgufModel { g.check_size()?; let override_file = embedding_override && snapshot.architecture.as_deref() == Some("strata-embd"); if !override_file { - if snapshot.architecture.as_deref() != Some("qwen4exp") { - return Err("native head architecture requires qwen4exp".into()); - } - for (key, want) in [ - ("qwen4exp.block_count", 48), - ("qwen4exp.embedding_length", 2560), - ("qwen4exp.expert_count", 0), - ("qwen4exp.expert_used_count", 0), - ("qwen4exp.attention.head_count", 24), - ("qwen4exp.attention.head_count_kv", 2), - ] { - let v = match snapshot.values.get(key) { - Some(MetadataValue::Unsigned(v)) => *v, - Some(MetadataValue::Signed(v)) => *v as u64, - _ => return Err(format!("native head: missing {key}").into()), - }; - if want != 0 && v != want { - return Err(format!("native head: {key} = {v}, expected {want}").into()); - } - } + check_head_profile(&snapshot)?; } Ok(Self { shards, names, embedding_override: override_file }) } @@ -149,40 +113,12 @@ impl NativeHeadGgufModel { self.load("token_embd.weight", n, vocab, true) } fn load(&mut self, name: &str, n: usize, vocab: usize, embedding: bool) -> Result { - if n == 0 || vocab == 0 || n > i32::MAX as usize || vocab > i32::MAX as usize || !n.is_multiple_of(256) { - return Err("native head positive int32/whole256 dimensions".into()); - } + check_dimensions(n, vocab)?; let &(shard, index) = self.names.get(name).ok_or("native output tensor absent")?; let g = &mut self.shards[shard]; - let t = &g.index.tensors[index]; - let supported = if embedding { - matches!(t.kind, 7 | 8 | 11 | 12 | 13 | 16 | 17 | 18 | 20 | 21 | 22 | 23 | 29 | 30 | 42) - } else { - matches!(t.kind, 2 | 6 | 7 | 8 | 11 | 12 | 13 | 14 | 16 | 17 | 18 | 20 | 21 | 22 | 23 | 29 | 42) - }; - if !supported || t.dimensions != [n as u64, vocab as u64] { - return Err("native output unsupported kind/shape".into()); - } - let bytes = - row_bytes(t.kind, n).and_then(|r| r.checked_mul(vocab)).ok_or("native output byte extent overflow")?; - let payload = - g.index.summary.file_size.checked_sub(g.index.summary.data_start).ok_or("native output payload extent")?; - if t.offset > payload || bytes as u64 > payload - t.offset || embedding && t.bytes != bytes as u64 { - return Err("native output tensor payload truncated/extent mismatch".into()); - } - let kind = t.kind; - let mut out = Vec::new(); - out.try_reserve_exact(bytes)?; - g.stream_tensor(index, 0, bytes as u64, |part| { - if out.len().checked_add(part.len()).is_none_or(|end| end > bytes) { - return Err(std::io::Error::from(std::io::ErrorKind::InvalidData)); - } - out.extend_from_slice(part); - Ok(()) - })?; - if out.len() != bytes { - return Err("native output incomplete payload".into()); - } + let bytes = head_extent(&g.index, index, n, vocab, embedding)?; + let kind = g.index.tensors[index].kind; + let out = read_head_bytes(g, index, bytes)?; Ok(NativeHeadTensor { kind, columns: n, @@ -193,3 +129,117 @@ impl NativeHeadGgufModel { }) } } + +/// Original split/order admission: a single shard is a whole model, several must be one complete split set. +fn check_shard_order(shards: &[VerifiedGgufFile]) -> Result<()> { + let first = &shards.first().ok_or("GGUF model has no shards")?.index.summary; + if shards.len() != 1 { + return check_split_set(shards, first); + } + if first.split_count.is_some_and(|count| count > 1) { + return Err("GGUF split model opened as a whole model".into()); + } + Ok(()) +} + +fn check_split_set(shards: &[VerifiedGgufFile], first: &Summary) -> Result<()> { + if first.architecture.is_none() { + return Err("GGUF first shard has no general.architecture".into()); + } + let total = first.split_tensors_count; + let mut count = 0u64; + for (i, g) in shards.iter().enumerate() { + check_shard_split(&g.index.summary, i, shards.len(), total)?; + count = count.checked_add(g.index.tensors.len() as u64).ok_or("GGUF tensor count overflow")?; + } + if total.is_some_and(|total| total != count) { + return Err("GGUF split tensor count mismatch".into()); + } + Ok(()) +} + +fn check_shard_split(s: &Summary, i: usize, n: usize, total: Option) -> Result<()> { + if s.split_count != Some(n as u64) + || s.split_no != Some(i as u64) + || total.is_some() && s.split_tensors_count != total + { + return Err("GGUF split metadata/order mismatch".into()); + } + Ok(()) +} + +/// Tensor name -> (shard, tensor number); a name in two shards is refused. +fn index_names(shards: &[VerifiedGgufFile]) -> Result> { + let mut names = BTreeMap::new(); + for (s, g) in shards.iter().enumerate() { + for (i, t) in g.index.tensors.iter().enumerate() { + if names.insert(t.name.clone(), (s, i)).is_some() { + return Err("GGUF duplicate tensor across shards".into()); + } + } + } + Ok(names) +} + +fn check_head_profile(snapshot: &MetadataSnapshot) -> Result<()> { + if snapshot.architecture.as_deref() != Some("qwen4exp") { + return Err("native head architecture requires qwen4exp".into()); + } + for (key, want) in HEAD_PROFILE { + let v = match snapshot.values.get(key) { + Some(MetadataValue::Unsigned(v)) => *v, + Some(MetadataValue::Signed(v)) => *v as u64, + _ => return Err(format!("native head: missing {key}").into()), + }; + if want != 0 && v != want { + return Err(format!("native head: {key} = {v}, expected {want}").into()); + } + } + Ok(()) +} + +fn check_dimensions(n: usize, vocab: usize) -> Result<()> { + if n == 0 || vocab == 0 || n > i32::MAX as usize || vocab > i32::MAX as usize || !n.is_multiple_of(256) { + return Err("native head positive int32/whole256 dimensions".into()); + } + Ok(()) +} + +fn kind_supported(kind: u32, embedding: bool) -> bool { + if embedding { + matches!(kind, 7 | 8 | 11 | 12 | 13 | 16 | 17 | 18 | 20 | 21 | 22 | 23 | 29 | 30 | 42) + } else { + matches!(kind, 2 | 6 | 7 | 8 | 11 | 12 | 13 | 14 | 16 | 17 | 18 | 20 | 21 | 22 | 23 | 29 | 42) + } +} + +/// The byte extent of tensor `tensor` as a `n` x `vocab` head or embedding, after the kind, shape and payload checks. +fn head_extent(index: &TensorIndex, tensor: usize, n: usize, vocab: usize, embedding: bool) -> Result { + let t = &index.tensors[tensor]; + if !kind_supported(t.kind, embedding) || t.dimensions != [n as u64, vocab as u64] { + return Err("native output unsupported kind/shape".into()); + } + let bytes = row_bytes(t.kind, n).and_then(|r| r.checked_mul(vocab)).ok_or("native output byte extent overflow")?; + let payload = + index.summary.file_size.checked_sub(index.summary.data_start).ok_or("native output payload extent")?; + if t.offset > payload || bytes as u64 > payload - t.offset || embedding && t.bytes != bytes as u64 { + return Err("native output tensor payload truncated/extent mismatch".into()); + } + Ok(bytes) +} + +fn read_head_bytes(g: &mut VerifiedGgufFile, tensor: usize, bytes: usize) -> Result> { + let mut out = Vec::new(); + out.try_reserve_exact(bytes)?; + g.stream_tensor(tensor, 0, bytes as u64, |part| { + if out.len().checked_add(part.len()).is_none_or(|end| end > bytes) { + return Err(std::io::Error::from(std::io::ErrorKind::InvalidData)); + } + out.extend_from_slice(part); + Ok(()) + })?; + if out.len() != bytes { + return Err("native output incomplete payload".into()); + } + Ok(out) +} diff --git a/crates/model-format/src/gguf_owned_read_test.rs b/crates/model-format/src/gguf_owned_read_test.rs index 846d0913..b95a3307 100644 --- a/crates/model-format/src/gguf_owned_read_test.rs +++ b/crates/model-format/src/gguf_owned_read_test.rs @@ -61,24 +61,44 @@ fn original(source: &mut VerifiedGgufFile, offset: u64, n: u64) -> Result File, offset: u64, n: usize) { + let mut old = open(); + let old_error = stream_file_span(&mut old, offset, n as u64, |_| panic!("failing consumer")).unwrap_err(); let old_cursor = old.stream_position().unwrap(); - let mut new = File::open(&path).unwrap(); - let error = read_file_span_owned(&mut new, 1, initialized(5)).unwrap_err(); - assert_eq!( - old_error.downcast_ref::().unwrap().kind(), - error.downcast_ref::().unwrap().kind() - ); - assert_eq!(new.stream_position().unwrap(), old_cursor); - let mut old = std::fs::OpenOptions::new().write(true).open(&path).unwrap(); - let old_error = stream_file_span(&mut old, 0, 3, |_| panic!("write-only consumer")).unwrap_err(); - let old_cursor = old.stream_position().unwrap(); - let mut new = std::fs::OpenOptions::new().write(true).open(&path).unwrap(); - let error = read_file_span_owned(&mut new, 0, initialized(3)).unwrap_err(); + let mut new = open(); + let error = read_file_span_owned(&mut new, offset, initialized(n)).unwrap_err(); assert_eq!( old_error.downcast_ref::().unwrap().kind(), error.downcast_ref::().unwrap().kind() diff --git a/crates/model-format/src/gguf_resident/impl_verifiedgguffile.rs b/crates/model-format/src/gguf_resident/impl_verifiedgguffile.rs index 5cbfb4b6..60b9c49a 100644 --- a/crates/model-format/src/gguf_resident/impl_verifiedgguffile.rs +++ b/crates/model-format/src/gguf_resident/impl_verifiedgguffile.rs @@ -3,6 +3,8 @@ #[allow(unused_imports)] use super::*; +type LoadResult = std::result::Result; + impl VerifiedGgufFile { /// Constructor is source-owned: arbitrary caller bytes cannot become a bank. pub(crate) fn load_resident_tensor( @@ -10,6 +12,21 @@ impl VerifiedGgufFile { tensor_number: usize, capacity_ceiling: usize, ) -> std::result::Result { + let (_, _, length) = self.resident_extent(tensor_number)?; + if length > capacity_ceiling { + return Err(ResidentLoadError::Budget); + } + // Existing descriptor/source-size admission precedes allocation. + self.stream_tensor(tensor_number, 0, 0, |_| Ok(())).map_err(ResidentLoadError::Source)?; + #[cfg(target_os = "linux")] + if crate::huge_pages::mode() != crate::huge_pages::Mode::Off { + return self.load_huge(tensor_number, length, capacity_ceiling); + } + self.load_heap(tensor_number, length, capacity_ceiling) + } + + /// (offset, bytes, length) of an indexed, non-empty tensor that fits the address space. + fn resident_extent(&self, tensor_number: usize) -> LoadResult<(u64, u64, usize)> { let tensor = self .index .tensors @@ -19,31 +36,33 @@ impl VerifiedGgufFile { if length == 0 { return Err(ResidentLoadError::Source("resident tensor is empty".into())); } - if length > capacity_ceiling { + Ok((tensor.offset, tensor.bytes, length)) + } + + /// The same bytes in a huge-page mapping instead of the heap; refusals map as for the heap copy. + #[cfg(target_os = "linux")] + fn load_huge( + &mut self, + tensor_number: usize, + length: usize, + capacity_ceiling: usize, + ) -> LoadResult { + let mut buffer = crate::huge_pages::HugeBuffer::allocate(length).map_err(|_| ResidentLoadError::Allocation)?; + let charged_bytes = buffer.charged_len(); + if charged_bytes > capacity_ceiling { return Err(ResidentLoadError::Budget); } - // Existing descriptor/source-size admission precedes allocation. - self.stream_tensor(tensor_number, 0, 0, |_| Ok(())).map_err(ResidentLoadError::Source)?; - #[cfg(target_os = "linux")] - if crate::huge_pages::mode() != crate::huge_pages::Mode::Off { - // The same bytes in a huge-page mapping instead of the heap; refusals map as for the heap copy. - let mut buffer = - crate::huge_pages::HugeBuffer::allocate(length).map_err(|_| ResidentLoadError::Allocation)?; - let charged_bytes = buffer.charged_len(); - if charged_bytes > capacity_ceiling { - return Err(ResidentLoadError::Budget); - } - self.read_tensor_into(tensor_number, 0, buffer.as_mut_slice()).map_err(ResidentLoadError::Source)?; - let source = match self.resident_source_id { - Some(source) => source, - None => { - let source = next_source_id().map_err(ResidentLoadError::Source)?; - self.resident_source_id = Some(source); - source - } - }; - return Ok(ResidentTensor { source, tensor_number, bytes: ResidentStorage::Huge(buffer), charged_bytes }); - } + self.read_tensor_into(tensor_number, 0, buffer.as_mut_slice()).map_err(ResidentLoadError::Source)?; + let source = self.source_id().map_err(ResidentLoadError::Source)?; + Ok(ResidentTensor { source, tensor_number, bytes: ResidentStorage::Huge(buffer), charged_bytes }) + } + + fn load_heap( + &mut self, + tensor_number: usize, + length: usize, + capacity_ceiling: usize, + ) -> LoadResult { let mut bytes = Vec::new(); bytes.try_reserve_exact(length).map_err(|_| ResidentLoadError::Allocation)?; let charged_bytes = bytes.capacity(); @@ -54,39 +73,48 @@ impl VerifiedGgufFile { let bytes = self.read_tensor_owned(tensor_number, 0, bytes.into_boxed_slice()).map_err(ResidentLoadError::Source)?; // The immutable real source owns this identity; no default allocation. - let source = match self.resident_source_id { - Some(source) => source, - None => { - let source = next_source_id().map_err(ResidentLoadError::Source)?; - self.resident_source_id = Some(source); - source - } - }; + let source = self.source_id().map_err(ResidentLoadError::Source)?; Ok(ResidentTensor { source, tensor_number, bytes: ResidentStorage::Owned(bytes), charged_bytes }) } + + /// The identity of this source, assigned on first use. + fn source_id(&mut self) -> Result { + if let Some(source) = self.resident_source_id { + return Ok(source); + } + let source = next_source_id()?; + self.resident_source_id = Some(source); + Ok(source) + } + /// The Original's `--mmap-experts` with the GGUF in place (`FileExpertSource::set_gguf`): the tensor's /// bytes are a read-only shared mapping of this verified file instead of a copy, so no RAM is committed /// for them; the OS file cache keeps what is read. Same descriptor, same indexed bounds and size checks /// as `load_resident_tensor`. `charged_bytes` is the mapped length (address space, not RAM). #[cfg(any(target_os = "linux", windows))] - #[allow(unsafe_code)] pub(crate) fn map_resident_tensor( &mut self, tensor_number: usize, ) -> std::result::Result { - let (tensor_offset, tensor_bytes) = { - let tensor = self - .index - .tensors - .get(tensor_number) - .ok_or_else(|| ResidentLoadError::Source("GGUF tensor index is out of bounds".into()))?; - (tensor.offset, tensor.bytes) - }; - let length = usize::try_from(tensor_bytes).map_err(|e| ResidentLoadError::Source(e.into()))?; - if length == 0 { - return Err(ResidentLoadError::Source("resident tensor is empty".into())); - } + let (tensor_offset, tensor_bytes, length) = self.resident_extent(tensor_number)?; self.stream_tensor(tensor_number, 0, 0, |_| Ok(())).map_err(ResidentLoadError::Source)?; + let absolute = self.mapped_absolute(tensor_offset, tensor_bytes)?; + let granularity = mapping_granularity(); + let map_offset = absolute & !(granularity - 1); + let start = usize::try_from(absolute - map_offset).map_err(|e| ResidentLoadError::Source(e.into()))?; + let map_len = + start.checked_add(length).ok_or_else(|| ResidentLoadError::Source("mapping length overflow".into()))?; + self.check_size().map_err(ResidentLoadError::Source)?; + let base = self.map_view(map_offset, map_len)?; + let span = FileSpan { base, map_len, start, len: length }; + self.check_size().map_err(ResidentLoadError::Source)?; + let source = self.source_id().map_err(ResidentLoadError::Source)?; + Ok(ResidentTensor { source, tensor_number, bytes: ResidentStorage::Mapped(span), charged_bytes: length }) + } + + /// The absolute file offset of a tensor, after the indexed-file bounds check. + #[cfg(any(target_os = "linux", windows))] + fn mapped_absolute(&self, tensor_offset: u64, tensor_bytes: u64) -> LoadResult { let absolute = self .index .summary @@ -96,19 +124,16 @@ impl VerifiedGgufFile { if absolute.checked_add(tensor_bytes).is_none_or(|end| end > self.index.summary.file_size) { return Err(ResidentLoadError::Source("GGUF tensor exceeds indexed file".into())); } - #[cfg(target_os = "linux")] - let page = rustix::param::page_size() as u64; - #[cfg(windows)] - let page = leleka_libc_shim::allocation_granularity(); - let map_offset = absolute & !(page - 1); - let start = usize::try_from(absolute - map_offset).map_err(|e| ResidentLoadError::Source(e.into()))?; - let map_len = - start.checked_add(length).ok_or_else(|| ResidentLoadError::Source("mapping length overflow".into()))?; - self.check_size().map_err(ResidentLoadError::Source)?; + Ok(absolute) + } + + /// A fresh read-only shared mapping of the retained verified descriptor. + #[cfg(target_os = "linux")] + #[allow(unsafe_code)] + fn map_view(&self, map_offset: u64, map_len: usize) -> LoadResult<*mut std::ffi::c_void> { // SAFETY: a fresh read-only shared mapping of the retained verified descriptor at a page-aligned // offset inside the indexed file; the kernel picks the address. No existing memory is replaced. - #[cfg(target_os = "linux")] - let base = unsafe { + unsafe { rustix::mm::mmap( std::ptr::null_mut(), map_len, @@ -118,32 +143,25 @@ impl VerifiedGgufFile { map_offset, ) } - .map_err(|e| ResidentLoadError::Source(Box::new(std::io::Error::from(e))))?; - // Windows: CreateFileMapping + MapViewOfFile(FILE_MAP_READ) of the retained verified handle; the view offset is - // a multiple of the 64 KiB allocation granularity (`page` above), the same layout as the Linux mapping. - #[cfg(windows)] - let base = { - use std::os::windows::io::AsRawHandle; - // SAFETY: a fresh read-only view of the retained verified handle at a granularity-aligned offset inside the indexed file. - let view = - unsafe { leleka_libc_shim::map_file_readonly(self.file.as_raw_handle().cast(), map_offset, map_len) }; - if view.is_null() { - return Err(ResidentLoadError::Source(Box::new(std::io::Error::last_os_error()))); - } - view - }; - let span = FileSpan { base, map_len, start, len: length }; - self.check_size().map_err(ResidentLoadError::Source)?; - let source = match self.resident_source_id { - Some(source) => source, - None => { - let source = next_source_id().map_err(ResidentLoadError::Source)?; - self.resident_source_id = Some(source); - source - } - }; - Ok(ResidentTensor { source, tensor_number, bytes: ResidentStorage::Mapped(span), charged_bytes: length }) + .map_err(|e| ResidentLoadError::Source(Box::new(std::io::Error::from(e)))) } + + /// Windows: CreateFileMapping + MapViewOfFile(FILE_MAP_READ) of the retained verified handle; the view offset is + /// a multiple of the 64 KiB allocation granularity (`mapping_granularity`), the same layout as the Linux mapping. + #[cfg(windows)] + #[allow(unsafe_code)] + fn map_view(&self, map_offset: u64, map_len: usize) -> LoadResult<*mut std::ffi::c_void> { + use std::os::windows::io::AsRawHandle; + // SAFETY: a fresh read-only view of the retained verified handle at a granularity-aligned offset inside the + // indexed file. + let view = + unsafe { leleka_libc_shim::map_file_readonly(self.file.as_raw_handle().cast(), map_offset, map_len) }; + if view.is_null() { + return Err(ResidentLoadError::Source(Box::new(std::io::Error::last_os_error()))); + } + Ok(view) + } + /// Copies a real source-owned bank span, with unchanged indexed bounds and /// same-FD pre/post size checks. A hit intentionally does not seek/read FD. pub(crate) fn copy_resident_tensor( @@ -155,8 +173,21 @@ impl VerifiedGgufFile { if self.resident_source_id != Some(resident.source) { return Err("resident tensor source identity mismatch".into()); } - let tensor = self.index.tensors.get(resident.tensor_number).ok_or("GGUF tensor index is out of bounds")?; let length = u64::try_from(output.len())?; + self.check_resident_span(resident, offset, length)?; + let first = usize::try_from(offset)?; + let end = first.checked_add(output.len()).ok_or("resident tensor offset overflow")?; + let selected = resident.bytes.as_slice().get(first..end).ok_or("resident tensor extent")?; + self.check_size()?; + output.copy_from_slice(selected); + self.check_size()?; + Ok(output) + } + + /// The indexed tensor of `resident` holds exactly its bytes, and `length` bytes at `offset` lie inside it and the + /// file. + fn check_resident_span(&self, resident: &ResidentTensor, offset: u64, length: u64) -> Result<()> { + let tensor = self.index.tensors.get(resident.tensor_number).ok_or("GGUF tensor index is out of bounds")?; if tensor.bytes == 0 || resident.bytes.len() as u64 != tensor.bytes || offset.checked_add(length).is_none_or(|end| end > tensor.bytes) @@ -173,15 +204,20 @@ impl VerifiedGgufFile { if absolute.checked_add(length).is_none_or(|end| end > self.index.summary.file_size) { return Err("GGUF tensor exceeds indexed file".into()); } - let first = usize::try_from(offset)?; - let end = first.checked_add(output.len()).ok_or("resident tensor offset overflow")?; - let selected = resident.bytes.as_slice().get(first..end).ok_or("resident tensor extent")?; - self.check_size()?; - output.copy_from_slice(selected); - self.check_size()?; - Ok(output) + Ok(()) } } + +#[cfg(target_os = "linux")] +fn mapping_granularity() -> u64 { + rustix::param::page_size() as u64 +} + +#[cfg(windows)] +fn mapping_granularity() -> u64 { + leleka_libc_shim::allocation_granularity() +} + impl GgufSourceFence<'_> { pub(crate) fn copy_resident_tensor( &self, diff --git a/crates/model-format/src/gguf_resident/impl_verifiedgguffile_2.rs b/crates/model-format/src/gguf_resident/impl_verifiedgguffile_2.rs index ce1f20b7..225f4921 100644 --- a/crates/model-format/src/gguf_resident/impl_verifiedgguffile_2.rs +++ b/crates/model-format/src/gguf_resident/impl_verifiedgguffile_2.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: impl VerifiedGgufFile, impl VerifiedGgufFile, impl ResidentTensor, impl VerifiedGgufFile. +//! Moved out of the parent module by STRA-338: impl VerifiedGgufFile, impl VerifiedGgufFile, impl ResidentTensor, impl +//! VerifiedGgufFile. #[allow(unused_imports)] use super::*; diff --git a/crates/model-format/src/gguf_resident/next_source_id.rs b/crates/model-format/src/gguf_resident/next_source_id.rs index 8c1a59ba..7b018cd2 100644 --- a/crates/model-format/src/gguf_resident/next_source_id.rs +++ b/crates/model-format/src/gguf_resident/next_source_id.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: fn next_source_id, impl ResidentTensor, impl ResidentStorage, impl std_ops_Deref, impl FileSpan, impl Drop_for_FileSpan. +//! Moved out of the parent module by STRA-338: fn next_source_id, impl ResidentTensor, impl ResidentStorage, impl +//! std_ops_Deref, impl FileSpan, impl Drop_for_FileSpan. #[allow(unused_imports)] use super::*; diff --git a/crates/model-format/src/gguf_resident_sdet.rs b/crates/model-format/src/gguf_resident_sdet.rs index 423353a6..29289b73 100644 --- a/crates/model-format/src/gguf_resident_sdet.rs +++ b/crates/model-format/src/gguf_resident_sdet.rs @@ -62,6 +62,27 @@ fn original_stream_first_resident_bank_bytes_source_fences_and_memory_admission( let fixture = Fixture::new(); let mut source = fixture.open(); let reference = original(&mut source, 0, 64).unwrap(); + let bank = check_budget_then_load(&mut source, &reference); + let identity = source.resident_source_id; + check_bank_spans(&mut source, &bank); + check_invalid_bank_spans(&mut source, &bank); + assert!(matches!(source.load_resident_tensor(1, 64), Err(ResidentLoadError::Source(_)))); + assert!(matches!(source.load_resident_tensor(0, 63), Err(ResidentLoadError::Budget))); + assert_eq!(source.resident_source_id, identity); + assert_eq!(&*bank.bytes, reference); + check_foreign_bank(&fixture, &mut source, &bank, identity); + check_replaced_path_and_length(&fixture, &mut source, &bank); + assert_eq!(source.resident_source_id, identity); + assert_eq!(&*bank.bytes, reference); + drop(bank); + drop(source); + drop(fixture); + check_read_failure_after_admission(); + check_memory_admission(); +} + +/// A bank over the budget is refused without an identity or a cursor move; within it, it is the original bytes. +fn check_budget_then_load(source: &mut VerifiedGgufFile, reference: &[u8]) -> ResidentTensor { let original_end = source.file.stream_position().unwrap(); assert!(matches!(source.load_resident_tensor(0, 63), Err(ResidentLoadError::Budget))); assert_eq!(source.resident_source_id, None); @@ -71,61 +92,64 @@ fn original_stream_first_resident_bank_bytes_source_fences_and_memory_admission( assert_eq!(bank.len(), 64); assert_eq!(bank.charged_bytes(), 64); assert_eq!(source.file.stream_position().unwrap(), original_end); - let identity = source.resident_source_id; + bank +} + +fn check_bank_spans(source: &mut VerifiedGgufFile, bank: &ResidentTensor) { for (offset, n) in [(0, 64), (3, 17), (63, 1), (16, 32), (64, 0)] { - let reference = original(&mut source, offset, n).unwrap(); + let reference = original(source, offset, n).unwrap(); source.file.seek(SeekFrom::Start(7)).unwrap(); let output = initialized(n); let pointer = output.as_ptr(); - let actual = source.copy_resident_tensor(&bank, offset, output).unwrap(); + let actual = source.copy_resident_tensor(bank, offset, output).unwrap(); assert_eq!(&*actual, reference); assert_eq!(actual.as_ptr(), pointer); assert_eq!(source.file.stream_position().unwrap(), 7); // Bank hit never seeks. } +} + +fn check_invalid_bank_spans(source: &mut VerifiedGgufFile, bank: &ResidentTensor) { for (offset, n) in [(64, 1), (u64::MAX, 4)] { source.file.seek(SeekFrom::Start(11)).unwrap(); - let old = original(&mut source, offset, n).unwrap_err(); - let new = source.copy_resident_tensor(&bank, offset, initialized(n)).unwrap_err(); + let old = original(source, offset, n).unwrap_err(); + let new = source.copy_resident_tensor(bank, offset, initialized(n)).unwrap_err(); assert_eq!(old.to_string(), new.to_string()); assert_eq!(source.file.stream_position().unwrap(), 11); } - assert!(matches!(source.load_resident_tensor(1, 64), Err(ResidentLoadError::Source(_)))); - assert!(matches!(source.load_resident_tensor(0, 63), Err(ResidentLoadError::Budget))); - assert_eq!(source.resident_source_id, identity); - assert_eq!(&*bank.bytes, reference); - // Same actual file, independently admitted FD: content equality is not source authority. +} + +/// Same actual file, independently admitted FD: content equality is not source authority. +fn check_foreign_bank(fixture: &Fixture, source: &mut VerifiedGgufFile, bank: &ResidentTensor, identity: Option) { let mut foreign = fixture.open(); let foreign_reference = original(&mut foreign, 0, 64).unwrap(); let foreign_bank = foreign.load_resident_tensor(0, 64).unwrap(); assert_eq!(&*foreign_bank.bytes, foreign_reference); assert_ne!(foreign.resident_source_id, identity); - assert!(foreign.copy_resident_tensor(&bank, 0, initialized(64)).is_err()); + assert!(foreign.copy_resident_tensor(bank, 0, initialized(64)).is_err()); assert!(source.copy_resident_tensor(&foreign_bank, 0, initialized(64)).is_err()); - // A replacement path occupant cannot change the already admitted real FD. +} + +/// A replacement path occupant cannot change the already admitted real FD; a changed length refuses. +fn check_replaced_path_and_length(fixture: &Fixture, source: &mut VerifiedGgufFile, bank: &ResidentTensor) { let retained = fixture.directory.join("retained.gguf"); std::fs::rename(&fixture.path, &retained).unwrap(); std::fs::write(&fixture.path, b"different pathname occupant").unwrap(); - let old = original(&mut source, 0, 64).unwrap(); + let old = original(source, 0, 64).unwrap(); source.file.seek(SeekFrom::Start(9)).unwrap(); - assert_eq!(&*source.copy_resident_tensor(&bank, 0, initialized(64)).unwrap(), old); + assert_eq!(&*source.copy_resident_tensor(bank, 0, initialized(64)).unwrap(), old); assert_eq!(source.file.stream_position().unwrap(), 9); std::fs::OpenOptions::new().write(true).open(&retained).unwrap().set_len((fixture.bytes.len() - 1) as u64).unwrap(); - let old = original(&mut source, 0, 64).unwrap_err(); - let new = source.copy_resident_tensor(&bank, 0, initialized(64)).unwrap_err(); + let old = original(source, 0, 64).unwrap_err(); + let new = source.copy_resident_tensor(bank, 0, initialized(64)).unwrap_err(); assert_eq!(old.to_string(), new.to_string()); assert!(matches!(source.load_resident_tensor(0, 64), Err(ResidentLoadError::Source(_)))); assert_eq!(source.file.stream_position().unwrap(), 9); - assert_eq!(source.resident_source_id, identity); - assert_eq!(&*bank.bytes, reference); - drop(foreign_bank); - drop(foreign); - drop(bank); - drop(source); - drop(fixture); +} - // Real read failure after zero-span admission, no published partial bank or ID. - // Test-only access substitutes a valid write-only FD for the same actual file; - // neither a source token nor ModelBinding is fabricated. +/// Real read failure after zero-span admission, no published partial bank or ID. +/// Test-only access substitutes a valid write-only FD for the same actual file; +/// neither a source token nor ModelBinding is fabricated. +fn check_read_failure_after_admission() { let fixture = Fixture::new(); let mut source = fixture.open(); source.file = std::fs::OpenOptions::new().write(true).open(&fixture.path).unwrap(); @@ -143,12 +167,11 @@ fn original_stream_first_resident_bank_bytes_source_fences_and_memory_admission( let bank = source.load_resident_tensor(0, 64).unwrap(); assert_eq!(&*bank.bytes, old); assert!(source.resident_source_id.is_some()); - drop(bank); - drop(source); - drop(fixture); +} - // Pure metadata, no /proc access or multi-GiB allocation. Independent exact - // capacity + 8 GiB boundary; malformed/missing snapshots must fail closed. +/// Pure metadata, no /proc access or multi-GiB allocation. Independent exact +/// capacity + 8 GiB boundary; malformed/missing snapshots must fail closed. +fn check_memory_admission() { let admit = crate::qwen4exp::test_resident_source_memory_admission; assert!(admit("MemTotal: 134217728 kB\nMemAvailable: 8388609 kB\n", 1024).is_ok()); assert!(admit("MemTotal: 134217728 kB\nMemAvailable: 8388608 kB\n", 1024).is_err()); diff --git a/crates/model-format/src/huge_pages.rs b/crates/model-format/src/huge_pages.rs index 19a3cbc5..582a6c08 100644 --- a/crates/model-format/src/huge_pages.rs +++ b/crates/model-format/src/huge_pages.rs @@ -12,10 +12,12 @@ //! lets the fault compact) and `MADV_POPULATE_WRITE` to fault the whole range in before the file is read into it. //! //! [`settle`] (called by the stack after the bank load and the shard page-cache drop, before the banks are page-locked) -//! reports the coverage from `/proc/self/smaps` and, when some 2 MiB ranges fell back to 4 KiB pages, asks the kernel to +//! reports the coverage from `/proc/self/smaps` and, when some 2 MiB ranges fell back to 4 KiB pages, asks the kernel +//! to //! collapse them synchronously (`MADV_COLLAPSE`, Linux 6.1+, independent of the THP sysfs knobs; best effort). //! -//! `LELEKA_HUGEPAGES=thp` skips the hugetlbfs attempt. `LELEKA_BANK_THP=on` (the older claude/decode-parity knob, which only +//! `LELEKA_HUGEPAGES=thp` skips the hugetlbfs attempt. `LELEKA_BANK_THP=on` (the older claude/decode-parity knob, which +//! only //! advised the unaligned heap `Vec`) now selects `thp` too. Off by default. The bytes are the file's either way: this //! changes where the banks live, never what they hold. No system setting is read-write here. #![allow(unsafe_code)] @@ -31,7 +33,8 @@ pub enum Mode { Thp, } -/// The mode of this process (`LELEKA_HUGEPAGES` = `on` | `thp` | `off`; unset = `off`, or `thp` with `LELEKA_BANK_THP=on`). +/// The mode of this process (`LELEKA_HUGEPAGES` = `on` | `thp` | `off`; unset = `off`, or `thp` with +/// `LELEKA_BANK_THP=on`). pub fn mode() -> Mode { static MODE: std::sync::OnceLock = std::sync::OnceLock::new(); *MODE.get_or_init(|| { @@ -86,6 +89,29 @@ mod linux { value.checked_add(to - 1).map(|v| v & !(to - 1)) } + fn invalid_input() -> std::io::Error { + std::io::Error::from(std::io::ErrorKind::InvalidInput) + } + + /// A fresh private anonymous read-write mapping of `len` bytes (the kernel picks the address); returns its start. + fn map_anonymous(len: usize) -> std::io::Result { + // SAFETY: a fresh private anonymous mapping; the kernel picks the address; nothing is replaced. + let p = unsafe { + libc::mmap( + std::ptr::null_mut(), + len, + libc::PROT_READ | libc::PROT_WRITE, + libc::MAP_PRIVATE | libc::MAP_ANONYMOUS, + -1, + 0, + ) + }; + if p == libc::MAP_FAILED { + return Err(std::io::Error::last_os_error()); + } + Ok(p as usize) + } + /// `HugePages_Free` x `Hugepagesize` of `/proc/meminfo` (0 when absent or unreadable). fn hugetlb_free_bytes() -> usize { let Ok(text) = std::fs::read_to_string("/proc/meminfo") else { return 0 }; @@ -105,52 +131,50 @@ mod linux { impl HugeBuffer { /// A zeroed, faulted-in buffer of `len` bytes (`len > 0`), or the OS error. The caller fills every byte. pub(crate) fn allocate(len: usize) -> std::io::Result { - let invalid = || std::io::Error::from(std::io::ErrorKind::InvalidInput); if len == 0 || mode() == Mode::Off { - return Err(invalid()); + return Err(invalid_input()); } - let page = rustix::param::page_size(); - if mode() == Mode::On { - let map_len = round_up(len, HUGE).ok_or_else(invalid)?; - if hugetlb_free_bytes() >= map_len { - // SAFETY: a fresh private anonymous mapping; the kernel picks the address; nothing is replaced. - let p = unsafe { - libc::mmap( - std::ptr::null_mut(), - map_len, - libc::PROT_READ | libc::PROT_WRITE, - libc::MAP_PRIVATE - | libc::MAP_ANONYMOUS - | libc::MAP_HUGETLB - | libc::MAP_HUGE_2MB - | libc::MAP_POPULATE, - -1, - 0, - ) - }; - if p != libc::MAP_FAILED { - return Ok(Self::register(p as usize, map_len, len, true)); - } - } + if mode() == Mode::On + && let Some(buffer) = Self::allocate_hugetlb(len)? + { + return Ok(buffer); + } + Self::allocate_thp(len) + } + + /// A `MAP_HUGETLB` mapping when the host has enough free hugetlbfs pages and the kernel grants it, else `None`. + fn allocate_hugetlb(len: usize) -> std::io::Result> { + let map_len = round_up(len, HUGE).ok_or_else(invalid_input)?; + if hugetlb_free_bytes() < map_len { + return Ok(None); } - let map_len = round_up(len, page).ok_or_else(invalid)?; - let reserve = map_len.checked_add(HUGE).ok_or_else(invalid)?; // SAFETY: a fresh private anonymous mapping; the kernel picks the address; nothing is replaced. let p = unsafe { libc::mmap( std::ptr::null_mut(), - reserve, + map_len, libc::PROT_READ | libc::PROT_WRITE, - libc::MAP_PRIVATE | libc::MAP_ANONYMOUS, + libc::MAP_PRIVATE + | libc::MAP_ANONYMOUS + | libc::MAP_HUGETLB + | libc::MAP_HUGE_2MB + | libc::MAP_POPULATE, -1, 0, ) }; if p == libc::MAP_FAILED { - return Err(std::io::Error::last_os_error()); + return Ok(None); } - let start = p as usize; - let base = round_up(start, HUGE).ok_or_else(invalid)?; + Ok(Some(Self::register(p as usize, map_len, len, true))) + } + + /// A 2 MiB-aligned anonymous mapping advised for transparent huge pages and faulted in. + fn allocate_thp(len: usize) -> std::io::Result { + let map_len = round_up(len, rustix::param::page_size()).ok_or_else(invalid_input)?; + let reserve = map_len.checked_add(HUGE).ok_or_else(invalid_input)?; + let start = map_anonymous(reserve)?; + let base = round_up(start, HUGE).ok_or_else(invalid_input)?; let (head, tail) = (base - start, reserve - (base - start) - map_len); // SAFETY: both trims lie inside the mapping just made and outside [base, base + map_len); page-aligned. unsafe { @@ -162,7 +186,14 @@ mod linux { } } let buffer = Self::register(base, map_len, len, false); - // SAFETY: advice over our own live mapping; MADV_HUGEPAGE changes no contents (EINVAL without THP support: ignored). + buffer.advise_and_populate()?; + Ok(buffer) + } + + fn advise_and_populate(&self) -> std::io::Result<()> { + let (base, map_len) = (self.base, self.map_len); + // SAFETY: advice over our own live mapping; MADV_HUGEPAGE changes no contents (EINVAL without THP support: + // ignored). unsafe { libc::madvise(base as *mut libc::c_void, map_len, libc::MADV_HUGEPAGE); } @@ -171,10 +202,10 @@ mod linux { if unsafe { libc::madvise(base as *mut libc::c_void, map_len, libc::MADV_POPULATE_WRITE) } != 0 { let error = std::io::Error::last_os_error(); if error.raw_os_error() != Some(libc::EINVAL) { - return Err(error); // ENOMEM and friends: `buffer` drops and unmaps + return Err(error); // ENOMEM and friends: the buffer drops and unmaps } } - Ok(buffer) + Ok(()) } fn register(base: usize, map_len: usize, len: usize, hugetlb: bool) -> Self { LIVE.lock().unwrap_or_else(|p| p.into_inner()).push((base, map_len, hugetlb)); @@ -190,7 +221,8 @@ mod linux { if self.hugetlb { self.map_len } else { self.len } } pub(crate) fn as_slice(&self) -> &[u8] { - // SAFETY: `base..base + map_len` is our live mapping and `len <= map_len`; anonymous memory is initialised (zero or written). + // SAFETY: `base..base + map_len` is our live mapping and `len <= map_len`; anonymous memory is initialised + // (zero or written). unsafe { std::slice::from_raw_parts(self.base as *const u8, self.len) } } pub(crate) fn as_mut_slice(&mut self) -> &mut [u8] { @@ -231,15 +263,19 @@ mod linux { mapped_bytes: live.iter().map(|e| e.1 as u64).sum(), ..Coverage::default() }; + add_smaps_totals(&smaps, &live, &mut out); + Some(out) + } + + /// Adds the huge-page fields of the smaps entries that overlap a live buffer. + fn add_smaps_totals(smaps: &str, live: &[(usize, usize, bool)], out: &mut Coverage) { let mut inside = false; for line in smaps.lines() { let mut words = line.split_whitespace(); let Some(first) = words.next() else { continue }; - if let Some((a, b)) = first.split_once('-').filter(|_| !first.ends_with(':')) { - if let (Ok(a), Ok(b)) = (usize::from_str_radix(a, 16), usize::from_str_radix(b, 16)) { - inside = live.iter().any(|&(base, len, _)| a < base + len && base < b); - continue; - } + if let Some((a, b)) = smaps_range(first) { + inside = live.iter().any(|&(base, len, _)| a < base + len && base < b); + continue; } if inside { let mut kib = || words.next().and_then(|v| v.parse::().ok()).unwrap_or(0) * 1024; @@ -250,7 +286,12 @@ mod linux { } } } - Some(out) + } + + /// The address range of a smaps entry header (`start-end perms ...`); `None` for any other line. + fn smaps_range(first: &str) -> Option<(usize, usize)> { + let (a, b) = first.split_once('-').filter(|_| !first.ends_with(':'))?; + Some((usize::from_str_radix(a, 16).ok()?, usize::from_str_radix(b, 16).ok()?)) } fn gib(bytes: u64) -> f64 { @@ -259,7 +300,11 @@ mod linux { fn line(label: &str, c: &Coverage) -> String { let huge = c.thp_bytes + c.hugetlb_bytes; format!( - "leleka-hugepages: {label}: {} bank buffers {:.2} GiB, huge {:.2} GiB ({:.1} %; THP {:.2}, hugetlbfs {:.2})", + concat!( + "leleka-hugepages: {}: {} bank buffers {:.2} GiB, huge {:.2} GiB ", + "({:.1} %; THP {:.2}, hugetlbfs {:.2})" + ), + label, c.buffers, gib(c.mapped_bytes), gib(huge), @@ -269,42 +314,20 @@ mod linux { ) } - /// Report the coverage and collapse the 2 MiB ranges that fell back to 4 KiB pages (`MADV_COLLAPSE`, synchronous, best - /// effort). Call before the banks are page-locked (a pinned page cannot be collapsed). `None` when nothing is placed. + /// Report the coverage and collapse the 2 MiB ranges that fell back to 4 KiB pages (`MADV_COLLAPSE`, synchronous, + /// best + /// effort). Call before the banks are page-locked (a pinned page cannot be collapsed). `None` when nothing is + /// placed. pub fn settle() -> Option { if mode() == Mode::Off { return None; } let before = coverage()?; let mut text = line("after fill", &before); - let aligned: u64 = LIVE - .lock() - .unwrap_or_else(|p| p.into_inner()) - .iter() - .filter(|e| !e.2) - .map(|e| (e.1 & !(HUGE - 1)) as u64) - .sum(); + let aligned: u64 = thp_ranges().iter().map(|r| r.1 as u64).sum(); if before.thp_bytes < aligned { let t = std::time::Instant::now(); - let ranges: Vec<(usize, usize)> = LIVE - .lock() - .unwrap_or_else(|p| p.into_inner()) - .iter() - .filter(|e| !e.2) - .map(|e| (e.0, e.1 & !(HUGE - 1))) - .collect(); - // linux/mman-common.h MADV_COLLAPSE = 25 (6.1+). Spelled out because libc 0.2.190 does not define it for the musl targets - // (the static CLI build failed to compile); glibc's libc::MADV_COLLAPSE has the same value. - const MADV_COLLAPSE: libc::c_int = 25; - let mut failed = 0usize; - let mut last_error = 0i32; - for (base, len) in ranges.into_iter().filter(|r| r.1 > 0) { - // SAFETY: advice over a live mapping of ours; MADV_COLLAPSE copies pages into a huge page without changing contents. - if unsafe { libc::madvise(base as *mut libc::c_void, len, MADV_COLLAPSE) } != 0 { - failed += 1; - last_error = std::io::Error::last_os_error().raw_os_error().unwrap_or(0); - } - } + let (failed, last_error) = collapse(&thp_ranges()); let after = coverage().unwrap_or(before); text.push_str(&format!( "\n{}; MADV_COLLAPSE {:.2} s, {failed} buffers incomplete (last errno {last_error})", @@ -315,6 +338,31 @@ mod linux { Some(text) } + /// The (base, whole-2-MiB-pages length) of every live transparent-huge-page buffer. + fn thp_ranges() -> Vec<(usize, usize)> { + let live = LIVE.lock().unwrap_or_else(|p| p.into_inner()); + live.iter().filter(|e| !e.2).map(|e| (e.0, e.1 & !(HUGE - 1))).collect() + } + + /// Asks the kernel to collapse each range into huge pages; returns (ranges that failed, last errno). + fn collapse(ranges: &[(usize, usize)]) -> (usize, i32) { + // linux/mman-common.h MADV_COLLAPSE = 25 (6.1+). Spelled out because libc 0.2.190 does not define it for the + // musl targets + // (the static CLI build failed to compile); glibc's libc::MADV_COLLAPSE has the same value. + const MADV_COLLAPSE: libc::c_int = 25; + let mut failed = 0usize; + let mut last_error = 0i32; + for &(base, len) in ranges.iter().filter(|r| r.1 > 0) { + // SAFETY: advice over a live mapping of ours; MADV_COLLAPSE copies pages into a huge page without changing + // contents. + if unsafe { libc::madvise(base as *mut libc::c_void, len, MADV_COLLAPSE) } != 0 { + failed += 1; + last_error = std::io::Error::last_os_error().raw_os_error().unwrap_or(0); + } + } + (failed, last_error) + } + #[cfg(test)] mod tests { use super::*; diff --git a/crates/model-format/src/kar.rs b/crates/model-format/src/kar.rs index 55c52b61..9511dff9 100644 --- a/crates/model-format/src/kar.rs +++ b/crates/model-format/src/kar.rs @@ -158,11 +158,13 @@ struct VerifiedPart { pub enum KarTrust { /// The whole archive was read once and matched its pinned SHA-256 and every section CRC-32. FullPass, - /// A verification stamp for exactly this file in exactly this state (device, inode, size, mtime, ctime) stood in for the pass. + /// A verification stamp for exactly this file in exactly this state (device, inode, size, mtime, ctime) stood in + /// for the pass. Stamp, /// The parent process copied this unlinked memfd from a stamped file and said so (`--kar-attested-by-stamp`). AttestedMemfd, - /// A sparse memfd (`verify_sparse`): the bytes of its extents matched the pinned digest of the extents; the rest is a hole. + /// A sparse memfd (`verify_sparse`): the bytes of its extents matched the pinned digest of the extents; the rest is + /// a hole. SparseExtents, } @@ -174,7 +176,8 @@ pub struct KarStartupRead { pub metadata_bytes: u64, /// The partition books (8 bytes each). pub book_bytes: u64, - /// Bytes hashed by the verification: the whole archive for `FullPass`, the extents for `SparseExtents`, otherwise 0. + /// Bytes hashed by the verification: the whole archive for `FullPass`, the extents for `SparseExtents`, otherwise + /// 0. pub hashed_bytes: u64, } @@ -190,12 +193,16 @@ pub struct VerifiedKarPleArtifact { /// Verified against a pinned digest of `serve_extents` instead of the whole archive (a sparse memfd). sparse: bool, startup: KarStartupRead, - /// The state of an ordinary archive file when it was verified (`None` for a sealed memfd, which cannot change, and where the - /// platform has no such fields). Every row read compares the open file with it: a write, `touch`, `chmod` or rename of the - /// file after verification refuses the read instead of serving bytes nobody checked. See `identity_recheck_enabled`. + /// The state of an ordinary archive file when it was verified (`None` for a sealed memfd, which cannot change, and + /// where the + /// platform has no such fields). Every row read compares the open file with it: a write, `touch`, `chmod` or rename + /// of the + /// file after verification refuses the read instead of serving bytes nobody checked. See + /// `identity_recheck_enabled`. identity: Option, } -/// Handles a row read spreads its threads over. On Windows each has a file object of its own (a synchronous handle serializes the +/// Handles a row read spreads its threads over. On Windows each has a file object of its own (a synchronous handle +/// serializes the /// requests made through it, whatever the number of threads: 100,000 random reads of a cold chunk took 10 s that way). const ROW_HANDLES: usize = 16; /// Rows of the PLE table read through an owned handle of the archive (`VerifiedKarPleArtifact::row_reader`): the same @@ -206,10 +213,13 @@ pub struct KarPleRowReader { archive_bytes: u64, identity: Option, } -/// A row read (three positional reads) that a warm file serves in this many nanoseconds or less takes the single-thread path. -/// Memory-served reads of 10-20 bytes take about 1 us each; a read that waits for a device takes tens of microseconds or more. +/// A row read (three positional reads) that a warm file serves in this many nanoseconds or less takes the single-thread +/// path. +/// Memory-served reads of 10-20 bytes take about 1 us each; a read that waits for a device takes tens of microseconds +/// or more. const WARM_ROW_NS: u128 = 20_000; -/// After a cold verdict the next calls read in parallel without probing (a cold file would pay the probe's latency each time). +/// After a cold verdict the next calls read in parallel without probing (a cold file would pay the probe's latency each +/// time). const COLD_SKIP_CALLS: u32 = 256; static COLD_SKIP: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); @@ -238,144 +248,8 @@ mod crc_slicing_tests; mod extents_tests; #[cfg(test)] -mod row_read_tests { - use super::*; - use std::io::Write; - use std::sync::atomic::Ordering; - - /// Two partitions over one synthetic file; every byte is below 0x70 so no scale reads as non-finite. - fn synthetic() -> (File, Vec, u64, std::path::PathBuf) { - let (n0, n1) = (1000u64, 500u64); - let scales0 = 0u64; - let planes0 = scales0 + n0 * 10; - let stride0 = n0 * 20; - let scales1 = planes0 + 2 * stride0; - let planes1 = scales1 + n1 * 10; - let stride1 = n1 * 20; - let total = planes1 + 2 * stride1; - let mut x = 0x9E37_79B9_7F4A_7C15u64; - let bytes: Vec = (0..total) - .map(|_| { - x ^= x << 13; - x ^= x >> 7; - x ^= x << 17; - (x % 0x70) as u8 - }) - .collect(); - // one file per call: the tests run in parallel and several of them touch, chmod or remove theirs - static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); - let unique = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed); - let path = std::env::temp_dir().join(format!("leleka-kar-rows-{}-{:x}-{unique}", std::process::id(), x)); - File::create(&path).unwrap().write_all(&bytes).unwrap(); - let parts = vec![ - VerifiedPart { row_base: 0, row_count: n0, scales: scales0, planes: planes0, stride: stride0 }, - VerifiedPart { row_base: n0, row_count: n1, scales: scales1, planes: planes1, stride: stride1 }, - ]; - (File::open(&path).unwrap(), parts, total, path) - } - - fn same(a: &[KarPleRowPacket], b: &[KarPleRowPacket]) -> bool { - a.len() == b.len() && a.iter().zip(b).all(|(x, y)| x.payload == y.payload && x.partition == y.partition) - } - - #[test] - fn the_warm_single_thread_read_returns_exactly_the_parallel_packets() { - let (file, parts, total, path) = synthetic(); - let files = vec![file.try_clone().unwrap(), file.try_clone().unwrap(), file.try_clone().unwrap()]; - let mut x = 7u64; - for case in 0..40 { - let rows: Vec = (0..16) - .map(|_| { - x = x.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); - (x >> 33) % 1500 - }) - .collect(); - // the reference: one thread, no probe - let mut reference = vec![KarPleRowPacket { payload: [0; 50], partition: 0 }; 16]; - read_rows_chunk(&file, &parts, &rows, &mut reference).unwrap(); - // the file is in the page cache: the probe takes the single-thread path (or, on a loaded machine, falls back to threads; - // the packets are the same either way) - COLD_SKIP.store(0, Ordering::Relaxed); - let probed = read_rows_parallel(&files, &parts, total, None, &rows, 8, 2, true).unwrap(); - assert!(same(&probed, &reference), "case {case}: probing read"); - // after a cold verdict the next calls skip the probe and read in parallel - COLD_SKIP.store(3, Ordering::Relaxed); - let parallel = read_rows_parallel(&files, &parts, total, None, &rows, 8, 2, true).unwrap(); - assert!(same(¶llel, &reference), "case {case}: parallel read after a cold verdict"); - assert_eq!(COLD_SKIP.load(Ordering::Relaxed), 2, "a skipped probe uses up one of the skip calls"); - let unprobed = read_rows_parallel(&files, &parts, total, None, &rows, 8, 2, false).unwrap(); - assert!(same(&unprobed, &reference), "case {case}: no probe"); - } - COLD_SKIP.store(0, Ordering::Relaxed); - // the refusals are the same as before: a row outside the table, a changed archive length - let bad = vec![PLE_ROWS; 16]; - assert!(matches!(read_rows_parallel(&files, &parts, total, None, &bad, 8, 2, true), Err(KarError::Range(_)))); - assert!(matches!( - read_rows_parallel(&files, &parts, total + 1, None, &[1, 2], 8, 2, true), - Err(KarError::Integrity(_)) - )); - // a row beyond the partitions' last row is a range error on the probe path as well - let beyond: Vec = (0..16).map(|i| 1500 + i).collect(); - assert!(read_rows_parallel(&files, &parts, total, None, &beyond, 8, 2, true).is_err()); - drop(files); - let _ = std::fs::remove_file(path); - } - - #[cfg(unix)] - #[test] - fn an_ordinary_archive_file_must_still_be_in_the_state_that_was_verified() { - use std::os::unix::fs::PermissionsExt; - let (file, parts, total, path) = synthetic(); - let id = crate::verify_stamp::FileIdentity::of(&file.metadata().unwrap()).unwrap(); - let files = vec![file.try_clone().unwrap()]; - let rows: Vec = vec![3, 999, 1000, 1400]; - let ok = read_rows_parallel(&files, &parts, total, Some(&id), &rows, 8, 2, false).unwrap(); - let reference = read_rows_parallel(&files, &parts, total, None, &rows, 8, 2, false).unwrap(); - assert!(same(&ok, &reference), "the check changes no byte that is returned"); - // a sealed memfd has no identity to compare: the length check alone - assert!(check_archive_state(&file, total, None).is_ok()); - assert!( - matches!(check_archive_state(&file, total + 1, Some(&id)), Err(KarError::Integrity(m)) if m.contains("length")) - ); - // the file is touched (mtime and ctime move, size and bytes do not): refused, on every entry point - std::thread::sleep(std::time::Duration::from_millis(30)); - let handle = std::fs::OpenOptions::new().write(true).open(&path).unwrap(); - handle.set_modified(std::time::SystemTime::now()).unwrap(); - drop(handle); - let refused = read_rows_parallel(&files, &parts, total, Some(&id), &rows, 8, 2, false); - assert!(matches!(refused, Err(KarError::Integrity(m)) if m.contains("changed since it was verified"))); - assert!(matches!(check_archive_state(&file, total, Some(&id)), Err(KarError::Integrity(_)))); - // the new state is a new identity: verifying again (and stamping) is how the service goes on - let id2 = crate::verify_stamp::FileIdentity::of(&file.metadata().unwrap()).unwrap(); - assert_ne!(id, id2); - assert!(read_rows_parallel(&files, &parts, total, Some(&id2), &rows, 8, 2, false).is_ok()); - // chmod alone moves ctime and is refused too - std::thread::sleep(std::time::Duration::from_millis(30)); - std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o400)).unwrap(); - assert!(matches!(check_archive_state(&file, total, Some(&id2)), Err(KarError::Integrity(_)))); - // the reader a prefill thread owns carries the same state - let reader = KarPleRowReader { - files: vec![file.try_clone().unwrap()], - parts: parts.clone(), - archive_bytes: total, - identity: Some(id2), - }; - assert!(matches!(reader.read_rows(&rows, 4), Err(KarError::Integrity(_)))); - let reader = KarPleRowReader { files, parts, archive_bytes: total, identity: None }; - assert!(same(&reader.read_rows(&rows, 4).unwrap(), &reference)); - let _ = std::fs::remove_file(path); - } - - #[test] - fn the_startup_figures_add_up() { - let read = KarStartupRead { trust: KarTrust::Stamp, metadata_bytes: 1_000, book_bytes: 16, hashed_bytes: 0 }; - assert_eq!(read.total_bytes(), 1_016); - assert_eq!(read.trust.as_str(), "stamp"); - let full = KarStartupRead { trust: KarTrust::FullPass, hashed_bytes: 55_295_529_472, ..read }; - assert_eq!(full.total_bytes(), 55_295_529_472 + 1_016); - assert_eq!((KarTrust::AttestedMemfd.as_str(), KarTrust::FullPass.as_str()), ("attested-memfd", "full-pass")); - } -} +#[path = "kar/row_read_tests.rs"] +mod row_read_tests; mod impl_std_fmt_display; #[allow(unused_imports)] diff --git a/crates/model-format/src/kar/decode_record_range.rs b/crates/model-format/src/kar/decode_record_range.rs index 67f5b5e5..f7c0dabc 100644 --- a/crates/model-format/src/kar/decode_record_range.rs +++ b/crates/model-format/src/kar/decode_record_range.rs @@ -17,15 +17,33 @@ pub(super) fn decode_record_range( return Err("CPU KAR decoder requires 1..=1,000,000 values within tensor bounds".into()); } if record[7] == 1 { - if record[41] != 0 { - return Err("CPU quality oracle only supports RAW F32 tensors".into()); - } - let offset = u64_at(record, 112) - .checked_add((start as u64).checked_mul(4).ok_or("KAR raw offset overflow")?) - .ok_or("KAR raw offset overflow")?; - let bytes = read_region(file, offset, count.checked_mul(4).ok_or("KAR raw byte count overflow")?)?; - return Ok(bytes.as_chunks::<4>().0.iter().map(|word| f32::from_le_bytes(*word)).collect()); + return decode_raw(file, record, start, count); } + decode_nested(file, record, level, (start, end), decoder) +} + +/// A RAW F32 tensor: `count` little-endian floats from element `start`. +fn decode_raw(file: &mut File, record: &[u8], start: usize, count: usize) -> Result, String> { + if record[41] != 0 { + return Err("CPU quality oracle only supports RAW F32 tensors".into()); + } + let offset = u64_at(record, 112) + .checked_add((start as u64).checked_mul(4).ok_or("KAR raw offset overflow")?) + .ok_or("KAR raw offset overflow")?; + let bytes = read_region(file, offset, count.checked_mul(4).ok_or("KAR raw byte count overflow")?)?; + Ok(bytes.as_chunks::<4>().0.iter().map(|word| f32::from_le_bytes(*word)).collect()) +} + +/// The groups of a nested tensor that cover the requested range. +struct Window { + group: u16, + base_group: usize, + end_group: usize, + base_element: usize, + local_padded: usize, +} + +fn decode_window(record: &[u8], level: u8, start: usize, end: usize) -> Result { let stored = record[42]; if level == 0 || level > stored { return Err(format!("KAR tensor stores 1..={stored} levels")); @@ -43,23 +61,49 @@ pub(super) fn decode_record_range( if base_element.checked_add(local_padded).is_none_or(|end| end > padded) { return Err("KAR decode range exceeds padded tensor".into()); } - let scale_bytes = read_region( - file, - u64_at(record, 64) - .checked_add((base_group as u64).checked_mul(2).ok_or("KAR scale offset overflow")?) - .ok_or("KAR scale offset overflow")?, - (end_group - base_group).checked_mul(2).ok_or("KAR scale byte count overflow")?, - )?; - let scales = - scale_bytes.as_chunks::<2>().0.iter().map(|pair| u16::from_le_bytes([pair[0], pair[1]])).collect::>(); - let book_offset = + Ok(Window { group, base_group, end_group, base_element, local_padded }) +} + +fn decode_nested( + file: &mut File, + record: &[u8], + level: u8, + (start, end): (usize, usize), + decoder: ScalarDecoder, +) -> Result, String> { + let window = decode_window(record, level, start, end)?; + let scales = read_scales(file, record, &window)?; + let book = read_level_book(file, record, level)?; + let planes = read_planes(file, record, &window, level)?; + let plane_refs = planes.iter().map(Vec::as_slice).collect::>(); + let count = end - start; + let mut output = Vec::new(); + output.try_reserve_exact(count).map_err(|_| "KAR allocation failed")?; + output.resize(count, 0.0); + decoder(&scales, &book, &plane_refs, window.group, start - window.base_element, &mut output)?; + Ok(output) +} + +fn read_scales(file: &mut File, record: &[u8], window: &Window) -> Result, String> { + let groups = window.end_group - window.base_group; + let offset = u64_at(record, 64) + .checked_add((window.base_group as u64).checked_mul(2).ok_or("KAR scale offset overflow")?) + .ok_or("KAR scale offset overflow")?; + let bytes = read_region(file, offset, groups.checked_mul(2).ok_or("KAR scale byte count overflow")?)?; + Ok(bytes.as_chunks::<2>().0.iter().map(|pair| u16::from_le_bytes([pair[0], pair[1]])).collect()) +} + +fn read_level_book(file: &mut File, record: &[u8], level: u8) -> Result, String> { + let offset = u64_at(record, 80).checked_add((1u64 << (u32::from(level) + 1)) - 4).ok_or("KAR book offset overflow")?; - let book_bytes = read_region(file, book_offset, (1usize << level) * 2)?; - let book = - book_bytes.as_chunks::<2>().0.iter().map(|pair| u16::from_le_bytes([pair[0], pair[1]])).collect::>(); + let bytes = read_region(file, offset, (1usize << level) * 2)?; + Ok(bytes.as_chunks::<2>().0.iter().map(|pair| u16::from_le_bytes([pair[0], pair[1]])).collect()) +} + +fn read_planes(file: &mut File, record: &[u8], window: &Window, level: u8) -> Result>, String> { let plane_stride = u64::from(u32_at(record, 104)); - let plane_bytes = local_padded / 32 * 4; - let plane_base = u64::try_from((base_element / 32).checked_mul(4).ok_or("KAR plane offset overflow")?) + let plane_bytes = window.local_padded / 32 * 4; + let plane_base = u64::try_from((window.base_element / 32).checked_mul(4).ok_or("KAR plane offset overflow")?) .map_err(|_| "KAR plane offset overflow")?; let mut planes = Vec::with_capacity(usize::from(level)); for plane in 0..u64::from(level) { @@ -77,10 +121,5 @@ pub(super) fn decode_record_range( .collect::>(), ); } - let plane_refs = planes.iter().map(Vec::as_slice).collect::>(); - let mut output = Vec::new(); - output.try_reserve_exact(count).map_err(|_| "KAR allocation failed")?; - output.resize(count, 0.0); - decoder(&scales, &book, &plane_refs, group, start - base_element, &mut output)?; - Ok(output) + Ok(planes) } diff --git a/crates/model-format/src/kar/impl_karpleprofile.rs b/crates/model-format/src/kar/impl_karpleprofile.rs index ebf96c47..aad30c3c 100644 --- a/crates/model-format/src/kar/impl_karpleprofile.rs +++ b/crates/model-format/src/kar/impl_karpleprofile.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: impl KarPleProfile, impl KarPleRowPacket, fn is_unlinked, fn is_unlinked, impl KarTrust, impl KarStartupRead. +//! Moved out of the parent module by STRA-338: impl KarPleProfile, impl KarPleRowPacket, fn is_unlinked, fn +//! is_unlinked, impl KarTrust, impl KarStartupRead. #[allow(unused_imports)] use super::*; @@ -11,40 +12,17 @@ impl KarPleProfile { } /// `new` for a table of `total_rows` rows: the pinned table has `PLE_ROWS`; tests build miniature archives. pub(super) fn with_total_rows(spec: KarPleProfileSpec, total_rows: u64) -> Result { - if spec.archive_bytes < 256 - || spec.virtual_f32_bytes == 0 - || spec.parts.is_empty() - || spec.parts.len() > 65535 - || spec.archive_sha256 == [0; 32] - || spec.provenance_sha256 == [0; 32] - || spec.virtual_f32_sha256 == [0; 32] - || spec.native_shard_sha256.contains(&[0; 32]) - { + if !profile_spec_valid(&spec) { return Err(KarError::Profile("invalid KAR PLE profile")); } let mut next = 0u64; let mut names = HashSet::new(); names.try_reserve(spec.parts.len()).map_err(|_| KarError::Allocation)?; for p in &spec.parts { - if p.name.is_empty() - || p.name.len() > 1024 - || p.name.bytes().any(|b| b < 32 || b == 127) - || !names.insert(p.name.as_str()) - || p.row_base != next - || p.row_count == 0 - || p.derived_f32_sha256 == [0; 32] - { + if !partition_valid(p, &mut names, next) { return Err(KarError::Profile("invalid KAR PLE partition provenance")); } - next = next - .checked_add(p.row_count) - .filter(|n| *n <= total_rows) - .ok_or(KarError::Range("KAR PLE row count overflow"))?; - p.row_count - .checked_mul(640) - .and_then(|n| p.derived_f32_offset.checked_add(n)) - .filter(|n| *n <= spec.virtual_f32_bytes) - .ok_or(KarError::Range("KAR PLE virtual source range"))?; + next = advance_partition(&spec, p, next, total_rows)?; } if next != total_rows { return Err(KarError::Profile("KAR PLE table extent mismatch")); @@ -55,6 +33,47 @@ impl KarPleProfile { &self.spec.native_shard_sha256 } } + +fn profile_spec_valid(spec: &KarPleProfileSpec) -> bool { + spec.archive_bytes >= 256 + && spec.virtual_f32_bytes != 0 + && !spec.parts.is_empty() + && spec.parts.len() <= 65535 + && spec.archive_sha256 != [0; 32] + && spec.provenance_sha256 != [0; 32] + && spec.virtual_f32_sha256 != [0; 32] + && !spec.native_shard_sha256.contains(&[0; 32]) +} + +/// The partition has a clean unique name, starts where the previous one ended and has rows and a source digest. +fn partition_valid<'a>(p: &'a KarPlePartProvenance, names: &mut HashSet<&'a str>, next: u64) -> bool { + !p.name.is_empty() + && p.name.len() <= 1024 + && !p.name.bytes().any(|b| b < 32 || b == 127) + && names.insert(p.name.as_str()) + && p.row_base == next + && p.row_count != 0 + && p.derived_f32_sha256 != [0; 32] +} + +/// The first row after `p`, once `p` is known to fit the table and the virtual source. +fn advance_partition( + spec: &KarPleProfileSpec, + p: &KarPlePartProvenance, + next: u64, + total_rows: u64, +) -> Result { + let end = next + .checked_add(p.row_count) + .filter(|n| *n <= total_rows) + .ok_or(KarError::Range("KAR PLE row count overflow"))?; + p.row_count + .checked_mul(640) + .and_then(|n| p.derived_f32_offset.checked_add(n)) + .filter(|n| *n <= spec.virtual_f32_bytes) + .ok_or(KarError::Range("KAR PLE virtual source range"))?; + Ok(end) +} impl KarPleRowPacket { pub fn payload(&self) -> &[u8; 50] { &self.payload diff --git a/crates/model-format/src/kar/impl_std_fmt_display.rs b/crates/model-format/src/kar/impl_std_fmt_display.rs index 11f428f6..6ae6d7c9 100644 --- a/crates/model-format/src/kar/impl_std_fmt_display.rs +++ b/crates/model-format/src/kar/impl_std_fmt_display.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: impl std_fmt_Display, impl std_error_Error, fn typed, impl KarTensorSource, impl KarInspection. +//! Moved out of the parent module by STRA-338: impl std_fmt_Display, impl std_error_Error, fn typed, impl +//! KarTensorSource, impl KarInspection. #[allow(unused_imports)] use super::*; @@ -17,6 +18,64 @@ impl std::error::Error for KarError { if let Self::Io(e) = self { Some(e) } else { None } } } +/// The messages the KAR parsers report as `KarError::Format` (anything else from them is an I/O failure). +const FORMAT_MESSAGES: &[&str] = &[ + "CPU KAR decoder requires 1..=1,000,000 values within tensor bounds", + "KAR accounted_bpw does not match archive size", + "KAR aggregate metadata mismatch", + "KAR archive length mismatch", + "KAR book offset overflow", + "KAR books offset overflow", + "KAR coded bit count overflow", + "KAR decode base overflow", + "KAR decode padded size overflow", + "KAR decode range exceeds padded tensor", + "KAR decode range overflow", + "KAR directory digest mismatch", + "KAR directory length overflow", + "KAR directory overflow", + "KAR group is zero", + "KAR header CRC-32 mismatch", + "KAR metadata exceeds bounded inspector limits", + "KAR model element count overflow", + "KAR name offset overflow", + "KAR padded count overflow", + "KAR padded tensor count mismatch", + "KAR plane offset overflow", + "KAR plane size overflow", + "KAR plane stride overflow", + "KAR planes offset overflow", + "KAR raw byte count overflow", + "KAR raw offset overflow", + "KAR raw tensor section is too small", + "KAR raw tensor size overflow", + "KAR scale byte count overflow", + "KAR scale count overflow", + "KAR scale offset overflow", + "KAR source identity differs from verified manifest shards", + "KAR string table overflow", + "KAR tensor bit count overflow", + "KAR tensor element count mismatch", + "KAR tensor is too large", + "KAR tensor name is not UTF-8", + "KAR tensor section overflow", + "KAR tensor sections are not contiguous or bounded", + "KAR tensor shape overflow", + "KARCHIV2", + "duplicate KAR tensor name", + "invalid KAR byte order or record size", + "invalid KAR flags, digest algorithm, or element counts", + "invalid KAR metadata offsets or alignment", + "invalid KAR nested tensor parameters", + "invalid KAR nested tensor section layout", + "invalid KAR raw tensor metadata", + "invalid KAR tensor name bounds", + "invalid KAR unused dimension", + "source manifest contains an invalid file name", + "unsupported KAR archive magic or version", + "unsupported KAR tensor layout", +]; + pub(super) fn typed(error: String) -> KarError { if error == "KAR allocation failed" { return KarError::Allocation; @@ -24,76 +83,9 @@ pub(super) fn typed(error: String) -> KarError { if error.contains("payload CRC-32 mismatch") { return KarError::Integrity("KAR payload CRC-32 mismatch"); } - match error.as_str() { - "CPU KAR decoder requires 1..=1,000,000 values within tensor bounds" => { - KarError::Format("CPU KAR decoder requires 1..=1,000,000 values within tensor bounds") - } - "KAR accounted_bpw does not match archive size" => { - KarError::Format("KAR accounted_bpw does not match archive size") - } - "KAR aggregate metadata mismatch" => KarError::Format("KAR aggregate metadata mismatch"), - "KAR archive length mismatch" => KarError::Format("KAR archive length mismatch"), - "KAR book offset overflow" => KarError::Format("KAR book offset overflow"), - "KAR books offset overflow" => KarError::Format("KAR books offset overflow"), - "KAR coded bit count overflow" => KarError::Format("KAR coded bit count overflow"), - "KAR decode base overflow" => KarError::Format("KAR decode base overflow"), - "KAR decode padded size overflow" => KarError::Format("KAR decode padded size overflow"), - "KAR decode range exceeds padded tensor" => KarError::Format("KAR decode range exceeds padded tensor"), - "KAR decode range overflow" => KarError::Format("KAR decode range overflow"), - "KAR directory digest mismatch" => KarError::Format("KAR directory digest mismatch"), - "KAR directory length overflow" => KarError::Format("KAR directory length overflow"), - "KAR directory overflow" => KarError::Format("KAR directory overflow"), - "KAR group is zero" => KarError::Format("KAR group is zero"), - "KAR header CRC-32 mismatch" => KarError::Format("KAR header CRC-32 mismatch"), - "KAR metadata exceeds bounded inspector limits" => { - KarError::Format("KAR metadata exceeds bounded inspector limits") - } - "KAR model element count overflow" => KarError::Format("KAR model element count overflow"), - "KAR name offset overflow" => KarError::Format("KAR name offset overflow"), - "KAR padded count overflow" => KarError::Format("KAR padded count overflow"), - "KAR padded tensor count mismatch" => KarError::Format("KAR padded tensor count mismatch"), - "KAR plane offset overflow" => KarError::Format("KAR plane offset overflow"), - "KAR plane size overflow" => KarError::Format("KAR plane size overflow"), - "KAR plane stride overflow" => KarError::Format("KAR plane stride overflow"), - "KAR planes offset overflow" => KarError::Format("KAR planes offset overflow"), - "KAR raw byte count overflow" => KarError::Format("KAR raw byte count overflow"), - "KAR raw offset overflow" => KarError::Format("KAR raw offset overflow"), - "KAR raw tensor section is too small" => KarError::Format("KAR raw tensor section is too small"), - "KAR raw tensor size overflow" => KarError::Format("KAR raw tensor size overflow"), - "KAR scale byte count overflow" => KarError::Format("KAR scale byte count overflow"), - "KAR scale count overflow" => KarError::Format("KAR scale count overflow"), - "KAR scale offset overflow" => KarError::Format("KAR scale offset overflow"), - "KAR source identity differs from verified manifest shards" => { - KarError::Format("KAR source identity differs from verified manifest shards") - } - "KAR string table overflow" => KarError::Format("KAR string table overflow"), - "KAR tensor bit count overflow" => KarError::Format("KAR tensor bit count overflow"), - "KAR tensor element count mismatch" => KarError::Format("KAR tensor element count mismatch"), - "KAR tensor is too large" => KarError::Format("KAR tensor is too large"), - "KAR tensor name is not UTF-8" => KarError::Format("KAR tensor name is not UTF-8"), - "KAR tensor section overflow" => KarError::Format("KAR tensor section overflow"), - "KAR tensor sections are not contiguous or bounded" => { - KarError::Format("KAR tensor sections are not contiguous or bounded") - } - "KAR tensor shape overflow" => KarError::Format("KAR tensor shape overflow"), - "KARCHIV2" => KarError::Format("KARCHIV2"), - "duplicate KAR tensor name" => KarError::Format("duplicate KAR tensor name"), - "invalid KAR byte order or record size" => KarError::Format("invalid KAR byte order or record size"), - "invalid KAR flags, digest algorithm, or element counts" => { - KarError::Format("invalid KAR flags, digest algorithm, or element counts") - } - "invalid KAR metadata offsets or alignment" => KarError::Format("invalid KAR metadata offsets or alignment"), - "invalid KAR nested tensor parameters" => KarError::Format("invalid KAR nested tensor parameters"), - "invalid KAR nested tensor section layout" => KarError::Format("invalid KAR nested tensor section layout"), - "invalid KAR raw tensor metadata" => KarError::Format("invalid KAR raw tensor metadata"), - "invalid KAR tensor name bounds" => KarError::Format("invalid KAR tensor name bounds"), - "invalid KAR unused dimension" => KarError::Format("invalid KAR unused dimension"), - "source manifest contains an invalid file name" => { - KarError::Format("source manifest contains an invalid file name") - } - "unsupported KAR archive magic or version" => KarError::Format("unsupported KAR archive magic or version"), - "unsupported KAR tensor layout" => KarError::Format("unsupported KAR tensor layout"), - _ => KarError::Io(std::io::Error::other(error)), + match FORMAT_MESSAGES.iter().find(|message| **message == error) { + Some(message) => KarError::Format(*message), + None => KarError::Io(std::io::Error::other(error)), } } diff --git a/crates/model-format/src/kar/impl_verifiedkarpleartifact.rs b/crates/model-format/src/kar/impl_verifiedkarpleartifact.rs index 3f74c4d6..4b870fb7 100644 --- a/crates/model-format/src/kar/impl_verifiedkarpleartifact.rs +++ b/crates/model-format/src/kar/impl_verifiedkarpleartifact.rs @@ -3,11 +3,15 @@ #[allow(unused_imports)] use super::*; +mod verify; +use verify::verify_archive; + impl VerifiedKarPleArtifact { pub fn verify(source: KarImmutableSource, profile: KarPleProfile) -> Result { Self::verify_with(source, profile, None) } - /// `verify` for a sealed memfd that holds only the bytes the serve path reads (holes elsewhere, same file offsets and + /// `verify` for a sealed memfd that holds only the bytes the serve path reads (holes elsewhere, same file offsets + /// and /// length): the full-archive SHA-256 and the payload CRCs cannot be computed, so the pinned `extents_sha256` /// ([`digest_extents_with`] over `serve_extents`, measured once from the archive that matched its full pin) stands /// in for them, and the directory digest in the header (checked by `inspect`, inside the extents) covers the rest. @@ -25,126 +29,17 @@ impl VerifiedKarPleArtifact { sparse_pin: Option<&[u8; 32]>, ) -> Result { let mut reader = source.inspection; - if reader.file.metadata().map_err(KarError::Io)?.len() != profile.spec.archive_bytes - || reader.summary.archive_bytes != profile.spec.archive_bytes - || reader.summary.source_bytes != profile.spec.virtual_f32_bytes - || reader.summary.source_digest != profile.spec.virtual_f32_sha256 - { - return Err(KarError::Integrity("KAR archive/provenance identity mismatch")); - } - // A stamp for exactly this file in exactly this state (see verify_stamp.rs) stands in for the full - // SHA-256 + CRC pass; a sealed memfd has no stable identity and always takes the full pass. - let identity = reader.file.metadata().ok().and_then(|m| crate::verify_stamp::FileIdentity::of(&m)); - let stamps = crate::verify_stamp::global(); - // An unlinked sealed memfd: only if the parent attested the copy (see `set_attested_archive`). - let attested_memfd = identity.is_none() && crate::verify_stamp::attested_archive() && is_unlinked(&reader.file); - let stamped = matches!((stamps, identity.as_ref()), (Some(s), Some(id)) if s.trusts("kar", &profile.spec.archive_sha256, id)); - let trusted = attested_memfd || stamped; - let trust = if sparse_pin.is_some() { - KarTrust::SparseExtents - } else if attested_memfd { - KarTrust::AttestedMemfd - } else if stamped { - KarTrust::Stamp - } else { - KarTrust::FullPass - }; - // A sparse copy never takes a stamp or an attestation: those speak for the whole archive, which it does not hold. - if sparse_pin.is_none() && !trusted { - reader.verify_integrity(profile.spec.archive_bytes, &profile.spec.archive_sha256)?; - if let (Some(stamps), Some(before)) = (stamps, identity) - && reader.file.metadata().ok().and_then(|m| crate::verify_stamp::FileIdentity::of(&m)) == Some(before) - { - let _ = stamps.record("kar", &profile.spec.archive_sha256, &before); - } - } - let mut parts = Vec::new(); - let mut books = Vec::new(); - let mut book_at_list = Vec::new(); - parts.try_reserve_exact(profile.spec.parts.len()).map_err(|_| KarError::Allocation)?; - books.try_reserve_exact(profile.spec.parts.len()).map_err(|_| KarError::Allocation)?; - for p in &profile.spec.parts { - let index = reader - .sources - .iter() - .position(|s| s.name == p.name) - .ok_or(KarError::Profile("KAR PLE partition missing"))?; - let s = &reader.sources[index]; - let record = &reader.directory[index * 192..(index + 1) * 192]; - if s.dimensions != [160, p.row_count] - || s.dtype != 0 - || s.storage_class != 0 - || record[45] != 0 - || u16_at(record, 46) != 32 - || s.planes_min > 2 - || s.planes_max < 2 - || s.digest != p.derived_f32_sha256 - || s.offset != p.derived_f32_offset - { - return Err(KarError::Profile("KAR PLE partition/source mapping mismatch")); - } - let scales = u64_at(record, 64); - let planes = s.planes_offset; - let stride = u64::from(s.plane_stride_bytes); - let book_at = u64_at(record, 80).checked_add(4).ok_or(KarError::Range("KAR PLE book overflow"))?; - let bytes = read_region(&mut reader.file, book_at, 8).map_err(typed)?; - let book = std::array::from_fn(|i| u16_at(&bytes, i * 2)); - if book.iter().any(|b| b & 0x7c00 == 0x7c00) { - return Err(KarError::Profile("KAR PLE nonfinite book")); - } - parts.push(VerifiedPart { row_base: p.row_base, row_count: p.row_count, scales, planes, stride }); - books.push(book); - book_at_list.push(book_at); - } - let serve_extents = normalize_extents( - &extents::exact_reads(reader.payload_offset, &parts, &book_at_list)?, - profile.spec.archive_bytes, - )?; - if let Some(pin) = sparse_pin { - // Every byte a row read can touch lies inside the extents (a row read is bounded by its partition), so no - // read can land in a hole; then the bytes of the extents must be the pinned ones. - for part in &parts { - for read in part.reads()? { - if !extents_cover(&serve_extents, read.offset, read.len) { - return Err(KarError::Range("KAR PLE read outside the sparse extents")); - } - } - } - let digest = digest_extents(&reader.file, &serve_extents, |_| {})?; - if &digest != pin { - return Err(KarError::Integrity("KAR sparse extents SHA-256 mismatch")); - } - } - let after = reader.file.metadata().map_err(KarError::Io)?; - if after.len() != profile.spec.archive_bytes { - return Err(KarError::Integrity("KAR archive length changed")); - } - // An ordinary file must be in the very state that was verified (or stamped) at the start of this call. - if identity.is_some() && crate::verify_stamp::FileIdentity::of(&after) != identity { - return Err(KarError::Integrity("KAR archive file changed while it was verified")); - } - let startup = KarStartupRead { - trust, - metadata_bytes: reader.metadata_bytes, - book_bytes: 8 * parts.len() as u64, - hashed_bytes: if sparse_pin.is_some() { - extents_bytes(&serve_extents) - } else if trusted { - 0 - } else { - profile.spec.archive_bytes - }, - }; + let checked = verify_archive(&mut reader, &profile, sparse_pin)?; Ok(Self { reader, profile, - parts, - books, + parts: checked.parts, + books: checked.books, handles: std::sync::OnceLock::new(), - serve_extents, + serve_extents: checked.serve_extents, sparse: sparse_pin.is_some(), - startup, - identity: if identity_recheck_enabled() { identity } else { None }, + startup: checked.startup, + identity: checked.identity, }) } /// The ranges of the archive the serve path reads (page-aligned, sorted, merged). @@ -186,9 +81,12 @@ impl VerifiedKarPleArtifact { if rows.iter().any(|r| *r >= PLE_ROWS) { return Err(KarError::Range("KAR PLE row outside table")); } - // 16 rows are 48 random reads of a cold file: eight threads on handles of their own, two rows each. A file the page cache - // holds answers each read in about a microsecond, and eight thread starts and joins then cost more than the reads - // (about 0.1 ms per token of a decode window); `warm_probe` reads the first row on this thread, times it, and reads the + // 16 rows are 48 random reads of a cold file: eight threads on handles of their own, two rows each. A file the + // page cache + // holds answers each read in about a microsecond, and eight thread starts and joins then cost more than the + // reads + // (about 0.1 ms per token of a decode window); `warm_probe` reads the first row on this thread, times it, and + // reads the // other fifteen here too when it was served from memory. let packets = read_rows_parallel( self.row_handles(), diff --git a/crates/model-format/src/kar/impl_verifiedkarpleartifact/verify.rs b/crates/model-format/src/kar/impl_verifiedkarpleartifact/verify.rs new file mode 100644 index 00000000..2a392472 --- /dev/null +++ b/crates/model-format/src/kar/impl_verifiedkarpleartifact/verify.rs @@ -0,0 +1,221 @@ +//! The checks `VerifiedKarPleArtifact::verify_with` runs on an inspected archive. + +#[allow(unused_imports)] +use super::*; + +type FileIdentity = crate::verify_stamp::FileIdentity; + +/// What a successful verification leaves behind. +pub(super) struct Checked { + pub(super) parts: Vec, + pub(super) books: Vec<[u16; 4]>, + pub(super) serve_extents: Vec, + pub(super) startup: KarStartupRead, + pub(super) identity: Option, +} + +/// How the archive is vouched for: a stamp for this very file, or the parent's attestation of a memfd. +struct Admission { + identity: Option, + stamps: Option<&'static crate::verify_stamp::VerifyStamps>, + attested_memfd: bool, + stamped: bool, +} + +fn current_identity(reader: &KarInspection) -> Option { + reader.file.metadata().ok().and_then(|m| FileIdentity::of(&m)) +} + +impl Admission { + fn decide(reader: &KarInspection, profile: &KarPleProfile) -> Self { + // A stamp for exactly this file in exactly this state (see verify_stamp.rs) stands in for the full + // SHA-256 + CRC pass; a sealed memfd has no stable identity and always takes the full pass. + let identity = current_identity(reader); + let stamps = crate::verify_stamp::global(); + // An unlinked sealed memfd: only if the parent attested the copy (see `set_attested_archive`). + let attested_memfd = identity.is_none() && crate::verify_stamp::attested_archive() && is_unlinked(&reader.file); + let stamped = match (stamps, identity.as_ref()) { + (Some(s), Some(id)) => s.trusts("kar", &profile.spec.archive_sha256, id), + _ => false, + }; + Self { identity, stamps, attested_memfd, stamped } + } + + fn trusted(&self) -> bool { + self.attested_memfd || self.stamped + } + + fn trust(&self, sparse: bool) -> KarTrust { + if sparse { + KarTrust::SparseExtents + } else if self.attested_memfd { + KarTrust::AttestedMemfd + } else if self.stamped { + KarTrust::Stamp + } else { + KarTrust::FullPass + } + } + + /// The whole-archive SHA-256 + CRC pass, unless a stamp or an attestation stands in for it. + /// A sparse copy never takes a stamp or an attestation: those speak for the whole archive, which it does not hold. + fn full_pass(&self, reader: &mut KarInspection, profile: &KarPleProfile, sparse: bool) -> Result<(), KarError> { + if sparse || self.trusted() { + return Ok(()); + } + reader.verify_integrity(profile.spec.archive_bytes, &profile.spec.archive_sha256)?; + if let (Some(stamps), Some(before)) = (self.stamps, self.identity) + && current_identity(reader) == Some(before) + { + let _ = stamps.record("kar", &profile.spec.archive_sha256, &before); + } + Ok(()) + } + + fn hashed_bytes(&self, sparse: bool, serve_extents: &[Extent], archive_bytes: u64) -> u64 { + if sparse { + extents_bytes(serve_extents) + } else if self.trusted() { + 0 + } else { + archive_bytes + } + } +} + +pub(super) fn verify_archive( + reader: &mut KarInspection, + profile: &KarPleProfile, + sparse_pin: Option<&[u8; 32]>, +) -> Result { + check_archive_identity(reader, profile)?; + let admission = Admission::decide(reader, profile); + admission.full_pass(reader, profile, sparse_pin.is_some())?; + let (parts, books, book_at_list) = verified_parts(reader, profile)?; + let serve_extents = normalize_extents( + &extents::exact_reads(reader.payload_offset, &parts, &book_at_list)?, + profile.spec.archive_bytes, + )?; + if let Some(pin) = sparse_pin { + check_sparse_extents(reader, &parts, &serve_extents, pin)?; + } + check_unchanged(reader, profile, admission.identity)?; + let sparse = sparse_pin.is_some(); + let startup = KarStartupRead { + trust: admission.trust(sparse), + metadata_bytes: reader.metadata_bytes, + book_bytes: 8 * parts.len() as u64, + hashed_bytes: admission.hashed_bytes(sparse, &serve_extents, profile.spec.archive_bytes), + }; + let identity = if identity_recheck_enabled() { admission.identity } else { None }; + Ok(Checked { parts, books, serve_extents, startup, identity }) +} + +fn check_archive_identity(reader: &KarInspection, profile: &KarPleProfile) -> Result<(), KarError> { + if reader.file.metadata().map_err(KarError::Io)?.len() != profile.spec.archive_bytes + || reader.summary.archive_bytes != profile.spec.archive_bytes + || reader.summary.source_bytes != profile.spec.virtual_f32_bytes + || reader.summary.source_digest != profile.spec.virtual_f32_sha256 + { + return Err(KarError::Integrity("KAR archive/provenance identity mismatch")); + } + Ok(()) +} + +type Parts = (Vec, Vec<[u16; 4]>, Vec); + +/// The partitions of the profile, found in the archive: their tables, their books and where each book lies. +fn verified_parts(reader: &mut KarInspection, profile: &KarPleProfile) -> Result { + let mut parts = Vec::new(); + let mut books = Vec::new(); + let mut book_at_list = Vec::new(); + parts.try_reserve_exact(profile.spec.parts.len()).map_err(|_| KarError::Allocation)?; + books.try_reserve_exact(profile.spec.parts.len()).map_err(|_| KarError::Allocation)?; + for p in &profile.spec.parts { + let (part, book, book_at) = verify_partition(reader, p)?; + parts.push(part); + books.push(book); + book_at_list.push(book_at); + } + Ok((parts, books, book_at_list)) +} + +fn verify_partition( + reader: &mut KarInspection, + p: &KarPlePartProvenance, +) -> Result<(VerifiedPart, [u16; 4], u64), KarError> { + let index = + reader.sources.iter().position(|s| s.name == p.name).ok_or(KarError::Profile("KAR PLE partition missing"))?; + let s = &reader.sources[index]; + let record = &reader.directory[index * 192..(index + 1) * 192]; + check_partition_mapping(s, record, p)?; + let scales = u64_at(record, 64); + let planes = s.planes_offset; + let stride = u64::from(s.plane_stride_bytes); + let book_at = u64_at(record, 80).checked_add(4).ok_or(KarError::Range("KAR PLE book overflow"))?; + let book = read_book(&mut reader.file, book_at)?; + let part = VerifiedPart { row_base: p.row_base, row_count: p.row_count, scales, planes, stride }; + Ok((part, book, book_at)) +} + +fn check_partition_mapping(s: &KarTensorSource, record: &[u8], p: &KarPlePartProvenance) -> Result<(), KarError> { + let layout_ok = s.dtype == 0 + && s.storage_class == 0 + && record[45] == 0 + && u16_at(record, 46) == 32 + && s.planes_min <= 2 + && s.planes_max >= 2; + let identity_ok = + s.dimensions == [160, p.row_count] && s.digest == p.derived_f32_sha256 && s.offset == p.derived_f32_offset; + if !layout_ok || !identity_ok { + return Err(KarError::Profile("KAR PLE partition/source mapping mismatch")); + } + Ok(()) +} + +fn read_book(file: &mut File, book_at: u64) -> Result<[u16; 4], KarError> { + let bytes = read_region(file, book_at, 8).map_err(typed)?; + let book = std::array::from_fn(|i| u16_at(&bytes, i * 2)); + if book.iter().any(|b| b & 0x7c00 == 0x7c00) { + return Err(KarError::Profile("KAR PLE nonfinite book")); + } + Ok(book) +} + +/// Every byte a row read can touch lies inside the extents (a row read is bounded by its partition), so no +/// read can land in a hole; then the bytes of the extents must be the pinned ones. +fn check_sparse_extents( + reader: &KarInspection, + parts: &[VerifiedPart], + serve_extents: &[Extent], + pin: &[u8; 32], +) -> Result<(), KarError> { + for part in parts { + for read in part.reads()? { + if !extents_cover(serve_extents, read.offset, read.len) { + return Err(KarError::Range("KAR PLE read outside the sparse extents")); + } + } + } + let digest = digest_extents(&reader.file, serve_extents, |_| {})?; + if &digest != pin { + return Err(KarError::Integrity("KAR sparse extents SHA-256 mismatch")); + } + Ok(()) +} + +fn check_unchanged( + reader: &KarInspection, + profile: &KarPleProfile, + identity: Option, +) -> Result<(), KarError> { + let after = reader.file.metadata().map_err(KarError::Io)?; + if after.len() != profile.spec.archive_bytes { + return Err(KarError::Integrity("KAR archive length changed")); + } + // An ordinary file must be in the very state that was verified (or stamped) at the start of this call. + if identity.is_some() && FileIdentity::of(&after) != identity { + return Err(KarError::Integrity("KAR archive file changed while it was verified")); + } + Ok(()) +} diff --git a/crates/model-format/src/kar/independent_handles.rs b/crates/model-format/src/kar/independent_handles.rs index 83c4eae2..10cd74fb 100644 --- a/crates/model-format/src/kar/independent_handles.rs +++ b/crates/model-format/src/kar/independent_handles.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: fn independent_handles, fn reopen_independent, fn reopen_independent, impl KarPleRowReader, fn read_rows_parallel, fn check_archive_state .... +//! Moved out of the parent module by STRA-338: fn independent_handles, fn reopen_independent, fn reopen_independent, +//! impl KarPleRowReader, fn read_rows_parallel, fn check_archive_state .... #[allow(unused_imports)] use super::*; @@ -66,47 +67,69 @@ pub(super) fn read_rows_parallel( packets.resize(rows.len(), KarPleRowPacket { payload: [0; 50], partition: 0 }); // positional reads of a file that is not in the page cache are latency-bound: many in flight let workers = (rows.len() / min_rows_per_thread.max(1)).clamp(1, max_threads.max(1)); - if warm_probe && workers > 1 { - use std::sync::atomic::Ordering; - if COLD_SKIP.load(Ordering::Relaxed) > 0 { - COLD_SKIP.fetch_sub(1, Ordering::Relaxed); - } else { - let started = std::time::Instant::now(); - read_rows_chunk(first, parts, &rows[..1], &mut packets[..1])?; - if started.elapsed().as_nanos() <= WARM_ROW_NS { - read_rows_chunk(first, parts, &rows[1..], &mut packets[1..])?; - return Ok(packets); - } - COLD_SKIP.store(COLD_SKIP_CALLS, Ordering::Relaxed); - } - } - if workers == 1 { - read_rows_chunk(first, parts, rows, &mut packets)?; - } else { - let per = rows.len().div_ceil(workers); - let results: Vec> = std::thread::scope(|scope| { - let handles: Vec<_> = rows - .chunks(per) - .zip(packets.chunks_mut(per)) - .enumerate() - .map(|(i, (rows, out))| { - let file = &files[i % files.len()]; - scope.spawn(move || read_rows_chunk(file, parts, rows, out)) - }) - .collect(); - handles - .into_iter() - .map(|h| h.join().unwrap_or(Err(KarError::Format("KAR PLE reader thread panicked")))) - .collect() - }); - for r in results { - r?; - } + if warm_probe && workers > 1 && read_warm(first, parts, rows, &mut packets)? { + return Ok(packets); } + read_fanned_out(files, parts, rows, &mut packets, workers)?; Ok(packets) } -/// The per-read guard of the archive: the pinned length, and for an ordinary file the state it had when it was verified. One `fstat` (the -/// length check always did one); a different size, modification time or change time (any write, `touch`, `chmod`, rename or hard link made + +/// Reads the first row on this thread and times it; a file the page cache holds answers in about a microsecond, and +/// then the other rows are read here too (true). After a cold verdict the next calls skip the probe (false). +fn read_warm( + first: &File, + parts: &[VerifiedPart], + rows: &[u64], + packets: &mut [KarPleRowPacket], +) -> Result { + use std::sync::atomic::Ordering; + if COLD_SKIP.load(Ordering::Relaxed) > 0 { + COLD_SKIP.fetch_sub(1, Ordering::Relaxed); + return Ok(false); + } + let started = std::time::Instant::now(); + read_rows_chunk(first, parts, &rows[..1], &mut packets[..1])?; + if started.elapsed().as_nanos() <= WARM_ROW_NS { + read_rows_chunk(first, parts, &rows[1..], &mut packets[1..])?; + return Ok(true); + } + COLD_SKIP.store(COLD_SKIP_CALLS, Ordering::Relaxed); + Ok(false) +} + +/// The rows over `workers` threads (one when `workers` is 1), each on a handle of its own. +fn read_fanned_out( + files: &[File], + parts: &[VerifiedPart], + rows: &[u64], + packets: &mut [KarPleRowPacket], + workers: usize, +) -> Result<(), KarError> { + if workers == 1 { + return read_rows_chunk(&files[0], parts, rows, packets); + } + let per = rows.len().div_ceil(workers); + let results: Vec> = std::thread::scope(|scope| { + let handles: Vec<_> = rows + .chunks(per) + .zip(packets.chunks_mut(per)) + .enumerate() + .map(|(i, (rows, out))| { + let file = &files[i % files.len()]; + scope.spawn(move || read_rows_chunk(file, parts, rows, out)) + }) + .collect(); + handles + .into_iter() + .map(|h| h.join().unwrap_or(Err(KarError::Format("KAR PLE reader thread panicked")))) + .collect() + }); + results.into_iter().collect() +} +/// The per-read guard of the archive: the pinned length, and for an ordinary file the state it had when it was +/// verified. One `fstat` (the +/// length check always did one); a different size, modification time or change time (any write, `touch`, `chmod`, +/// rename or hard link made /// after verification) is refused rather than served. pub(super) fn check_archive_state( file: &File, @@ -125,7 +148,8 @@ pub(super) fn check_archive_state( Ok(()) } -/// `LELEKA_KAR_IDENTITY_RECHECK=off` (or `0`) turns the per-read comparison with the verified file state off (a file system that does not +/// `LELEKA_KAR_IDENTITY_RECHECK=off` (or `0`) turns the per-read comparison with the verified file state off (a file +/// system that does not /// keep `ctime` stable, for example). Read once; the default is on. pub(super) fn identity_recheck_enabled() -> bool { static ENABLED: std::sync::OnceLock = std::sync::OnceLock::new(); @@ -144,35 +168,51 @@ pub(super) fn read_rows_chunk( out: &mut [KarPleRowPacket], ) -> Result<(), KarError> { for (row, packet) in rows.iter().zip(out) { - let index = parts - .partition_point(|p| p.row_base <= *row) - .checked_sub(1) - .ok_or(KarError::Range("KAR PLE partition range"))?; - let p = &parts[index]; - let local = row - p.row_base; - if local >= p.row_count { - return Err(KarError::Range("KAR PLE local row range")); - } - let scale = p - .scales - .checked_add(local.checked_mul(10).ok_or(KarError::Range("KAR PLE scale overflow"))?) - .ok_or(KarError::Range("KAR PLE scale overflow"))?; - read_at(file, scale, &mut packet.payload[..10])?; - for plane in 0..2usize { - let at = p - .planes - .checked_add((plane as u64).checked_mul(p.stride).ok_or(KarError::Range("KAR PLE plane overflow"))?) - .and_then(|at| local.checked_mul(20).and_then(|n| at.checked_add(n))) - .ok_or(KarError::Range("KAR PLE plane overflow"))?; - read_at(file, at, &mut packet.payload[10 + plane * 20..30 + plane * 20])?; - } - if packet.payload[..10].as_chunks::<2>().0.iter().any(|b| u16::from_le_bytes(*b) & 0x7c00 == 0x7c00) { - return Err(KarError::Profile("KAR PLE nonfinite scale")); - } - packet.partition = u16::try_from(index).map_err(|_| KarError::Range("KAR PLE partition index"))?; + read_row(file, parts, *row, packet)?; } Ok(()) } + +fn read_row(file: &File, parts: &[VerifiedPart], row: u64, packet: &mut KarPleRowPacket) -> Result<(), KarError> { + let index = parts + .partition_point(|p| p.row_base <= row) + .checked_sub(1) + .ok_or(KarError::Range("KAR PLE partition range"))?; + let p = &parts[index]; + let local = row - p.row_base; + if local >= p.row_count { + return Err(KarError::Range("KAR PLE local row range")); + } + read_payload(file, p, local, packet)?; + if packet.payload[..10].as_chunks::<2>().0.iter().any(|b| u16::from_le_bytes(*b) & 0x7c00 == 0x7c00) { + return Err(KarError::Profile("KAR PLE nonfinite scale")); + } + packet.partition = u16::try_from(index).map_err(|_| KarError::Range("KAR PLE partition index"))?; + Ok(()) +} + +/// The three positional reads of one row: its scales, then the two planes. +fn read_payload(file: &File, p: &VerifiedPart, local: u64, packet: &mut KarPleRowPacket) -> Result<(), KarError> { + read_at(file, scale_offset(p, local)?, &mut packet.payload[..10])?; + for plane in 0..2usize { + let at = plane_offset(p, plane, local)?; + read_at(file, at, &mut packet.payload[10 + plane * 20..30 + plane * 20])?; + } + Ok(()) +} + +fn scale_offset(p: &VerifiedPart, local: u64) -> Result { + p.scales + .checked_add(local.checked_mul(10).ok_or(KarError::Range("KAR PLE scale overflow"))?) + .ok_or(KarError::Range("KAR PLE scale overflow")) +} + +fn plane_offset(p: &VerifiedPart, plane: usize, local: u64) -> Result { + p.planes + .checked_add((plane as u64).checked_mul(p.stride).ok_or(KarError::Range("KAR PLE plane overflow"))?) + .and_then(|at| local.checked_mul(20).and_then(|n| at.checked_add(n))) + .ok_or(KarError::Range("KAR PLE plane overflow")) +} #[cfg(unix)] pub(super) fn read_at(file: &File, offset: u64, buffer: &mut [u8]) -> Result<(), KarError> { use std::os::unix::fs::FileExt; diff --git a/crates/model-format/src/kar/inspect_file.rs b/crates/model-format/src/kar/inspect_file.rs index 2a1ebde5..0408a7fa 100644 --- a/crates/model-format/src/kar/inspect_file.rs +++ b/crates/model-format/src/kar/inspect_file.rs @@ -3,235 +3,50 @@ #[allow(unused_imports)] use super::*; +mod header; +mod nested; +mod records; + +use header::KarHeader; +use records::RecordScan; + pub(super) fn inspect_file(mut file: File) -> Result { let file_bytes = file.metadata().map_err(|error| error.to_string())?.len(); - let header = read_region(&mut file, 0, HEADER_BYTES)?; - if &header[0..8] != b"KARCHIV2" || u32_at(&header, 8) != 2 { - return Err("unsupported KAR archive magic or version".into()); - } - if u32_at(&header, 12) != 0x04030201 - || u32_at(&header, 16) != HEADER_BYTES as u32 - || u32_at(&header, 20) != RECORD_BYTES as u32 - { - return Err("invalid KAR byte order or record size".into()); - } - if crc32(&header[..192]) != u32_at(&header, 192) { - return Err("KAR header CRC-32 mismatch".into()); - } - let directory_offset = u64_at(&header, 24); - let tensor_count = u32_at(&header, 32); - let string_offset = u64_at(&header, 40); - let string_bytes = u64_at(&header, 48); - let payload_offset = u64_at(&header, 56); - let archive_bytes = u64_at(&header, 64); - let total_elements = u64_at(&header, 72); - let payload_bits = u64_at(&header, 80); - let source_total_elements = u64_at(&header, 88); - let source_bytes = u64_at(&header, 120); - let accounted_bpw = f64::from_le_bytes(header[96..104].try_into().unwrap()); - let mut source_digest = [0; 32]; - source_digest.copy_from_slice(&header[128..160]); - if archive_bytes != file_bytes || archive_bytes < HEADER_BYTES as u64 { - return Err("KAR archive length mismatch".into()); - } - if tensor_count == 0 || tensor_count as usize > MAX_TENSORS || string_bytes > MAX_NAMES as u64 { - return Err("KAR metadata exceeds bounded inspector limits".into()); - } - if u32_at(&header, 36) != 0 - || header[106] != 1 - || total_elements == 0 - || total_elements > source_total_elements - || source_bytes == 0 - { - return Err("invalid KAR flags, digest algorithm, or element counts".into()); - } - let expected_bpw = archive_bytes as f64 * 8.0 / total_elements as f64; - if !accounted_bpw.is_finite() || ((accounted_bpw - expected_bpw) / expected_bpw).abs() > 2f64.powi(-40) { - return Err("KAR accounted_bpw does not match archive size".into()); - } - let directory_bytes = - (tensor_count as u64).checked_mul(RECORD_BYTES as u64).ok_or("KAR directory length overflow")?; - let directory_end = directory_offset.checked_add(directory_bytes).ok_or("KAR directory overflow")?; - let string_end = string_offset.checked_add(string_bytes).ok_or("KAR string table overflow")?; - if !directory_offset.is_multiple_of(64) - || !string_offset.is_multiple_of(64) - || !payload_offset.is_multiple_of(256) - || directory_offset < HEADER_BYTES as u64 - || directory_end > string_offset - || string_end > payload_offset - || payload_offset > archive_bytes - { - return Err("invalid KAR metadata offsets or alignment".into()); - } - let names = read_region(&mut file, string_offset, string_bytes as usize)?; - let directory = read_region(&mut file, directory_offset, directory_bytes as usize)?; - let mut digest = Sha256::new(); - digest.update(&names); - digest.update(&directory); - if digest.finalize().as_slice() != &header[160..192] { - return Err("KAR directory digest mismatch".into()); - } - - let mut seen_names = HashSet::new(); - seen_names.try_reserve(tensor_count as usize).map_err(|_| "KAR allocation failed")?; - let mut elements_sum = 0u64; - let mut bits_sum = 0u64; - let mut previous_end = payload_offset; - let mut min_planes = u8::MAX; - let mut max_planes = 0u8; - let mut sections = Vec::new(); - sections.try_reserve_exact(tensor_count as usize).map_err(|_| "KAR allocation failed")?; - let mut sources = Vec::new(); - sources.try_reserve_exact(tensor_count as usize).map_err(|_| "KAR allocation failed")?; + let header_bytes = read_region(&mut file, 0, HEADER_BYTES)?; + let header = KarHeader::parse(&header_bytes, file_bytes)?; + let (names, directory) = read_tables(&mut file, &header, &header_bytes)?; + let mut scan = RecordScan::new(&header)?; let (records, remainder) = directory.as_chunks::(); debug_assert!(remainder.is_empty()); for record in records { - let name_start = u32_at(record, 0) as usize; - let name_len = u16_at(record, 4) as usize; - let name_end = name_start.checked_add(name_len).ok_or("KAR name offset overflow")?; - if name_end >= names.len() || names[name_end] != 0 { - return Err("invalid KAR tensor name bounds".into()); - } - let name = std::str::from_utf8(&names[name_start..name_end]).map_err(|_| "KAR tensor name is not UTF-8")?; - if !seen_names.insert(name) { - return Err("duplicate KAR tensor name".into()); - } - let n_dims = record[6] as usize; - let storage = record[7]; - if !(1..=4).contains(&n_dims) || storage > 1 || record[40] != 0 || record[41] > 2 { - return Err("unsupported KAR tensor layout".into()); - } - let dims = (0..4).map(|index| u64_at(record, 8 + index * 8)).collect::>(); - if dims[n_dims..].iter().any(|dim| *dim != 1) { - return Err("invalid KAR unused dimension".into()); - } - let product = dims[..n_dims] - .iter() - .try_fold(1u64, |acc, dim| acc.checked_mul(*dim)) - .ok_or("KAR tensor shape overflow")?; - let n_elements = u64_at(record, 48); - if product != n_elements || n_elements == 0 { - return Err("KAR tensor element count mismatch".into()); - } - elements_sum = elements_sum.checked_add(n_elements).ok_or("KAR model element count overflow")?; - let mut source_digest = [0u8; 32]; - source_digest.copy_from_slice(&record[128..160]); - sources.push(KarTensorSource { - name: name.to_owned(), - dimensions: dims[..n_dims].to_vec(), - dtype: record[41], - digest: source_digest, - offset: u64_at(record, 160), - section_bytes: u64_at(record, 120), - storage_class: storage, - n_elements, - planes_min: record[43], - planes_max: record[44], - section_offset: u64_at(record, 112), - planes_offset: u64_at(record, 96), - plane_stride_bytes: u32_at(record, 104), - }); - let section_offset = u64_at(record, 112); - let section_bytes = u64_at(record, 120); - let section_end = section_offset.checked_add(section_bytes).ok_or("KAR tensor section overflow")?; - if section_offset != previous_end || !section_offset.is_multiple_of(256) || section_end > archive_bytes { - return Err("KAR tensor sections are not contiguous or bounded".into()); - } - previous_end = section_end; - sections.push(Section { offset: section_offset, bytes: section_bytes, crc32: u32_at(record, 108) }); - if storage == 0 { - let group = u16_at(record, 46) as u64; - let planes = record[42]; - let n_padded = u64_at(record, 56); - if group == 0 - || group > 1024 - || !group.is_multiple_of(32) - || !(1..=16).contains(&planes) - || record[43] == 0 - || record[43] > record[44] - || record[44] > planes - || record[45] > 1 - { - return Err("invalid KAR nested tensor parameters".into()); - } - let rounded = n_elements.div_ceil(group).checked_mul(group).ok_or("KAR padded count overflow")?; - if n_padded != rounded { - return Err("KAR padded tensor count mismatch".into()); - } - let scales_offset = u64_at(record, 64); - let scales_bytes = u64_at(record, 72); - let books_offset = u64_at(record, 80); - let books_bytes = u64_at(record, 88); - let planes_offset = u64_at(record, 96); - let stride = u32_at(record, 104) as u64; - let expected_scales = (n_padded / group).checked_mul(2).ok_or("KAR scale count overflow")?; - let expected_books = (1u64 << (planes as u32 + 2)) - 4; - let plane_words_bytes = (n_padded / 32).checked_mul(4).ok_or("KAR plane size overflow")?; - let expected_stride = round_up(plane_words_bytes, 16).ok_or("KAR plane stride overflow")?; - let books_start = scales_offset - .checked_add(scales_bytes) - .and_then(|value| round_up(value, 16)) - .ok_or("KAR books offset overflow")?; - let planes_start = books_offset - .checked_add(books_bytes) - .and_then(|value| round_up(value, 16)) - .ok_or("KAR planes offset overflow")?; - if scales_offset != section_offset - || scales_bytes != expected_scales - || books_offset != books_start - || books_bytes != expected_books - || planes_offset != planes_start - || stride != expected_stride - || planes_offset.checked_add(planes as u64 * stride).is_none_or(|end| end > section_end) - { - return Err("invalid KAR nested tensor section layout".into()); - } - let tensor_bits = (planes as u64) - .checked_mul(n_padded) - .and_then(|bits| (n_padded / group).checked_mul(16).and_then(|scale_bits| bits.checked_add(scale_bits))) - .ok_or("KAR tensor bit count overflow")?; - bits_sum = bits_sum.checked_add(tensor_bits).ok_or("KAR coded bit count overflow")?; - min_planes = min_planes.min(record[43]); - max_planes = max_planes.max(record[44]); - } else { - if record[42..48].iter().any(|value| *value != 0) - || u64_at(record, 56) != n_elements - || record[64..104].iter().any(|value| *value != 0) - || u32_at(record, 104) != 0 - { - return Err("invalid KAR raw tensor metadata".into()); - } - let width = if record[41] == 0 { 4 } else { 2 }; - if section_bytes < n_elements.checked_mul(width).ok_or("KAR raw tensor size overflow")? { - return Err("KAR raw tensor section is too small".into()); - } - } + scan.record(&header, &names, record)?; } - if previous_end != archive_bytes - || elements_sum != total_elements - || bits_sum != payload_bits - || header[104] != if min_planes == u8::MAX { 0 } else { min_planes } - || header[105] != max_planes - { - return Err("KAR aggregate metadata mismatch".into()); - } - let summary = KarSummary { - archive_bytes, - tensor_count, - total_elements, - source_total_elements, - accounted_bpw, - source_digest, - source_bytes, - max_planes, - }; + scan.finish(&header, &header_bytes)?; Ok(Parsed { - summary, + summary: header.summary(scan.max_planes), file, - sections, - sources, + sections: scan.sections, + sources: scan.sources, directory, - payload_offset, - metadata_bytes: HEADER_BYTES as u64 + string_bytes + directory_bytes, + payload_offset: header.payload_offset, + metadata_bytes: HEADER_BYTES as u64 + header.string_bytes + header.directory_bytes, }) } + +/// The name table and the directory, after their digest matched the header's. +fn read_tables(file: &mut File, header: &KarHeader, header_bytes: &[u8]) -> Result<(Vec, Vec), String> { + let names = read_region(file, header.string_offset, header.string_bytes as usize)?; + let directory = read_region(file, header.directory_offset, header.directory_bytes as usize)?; + check_directory_digest(header_bytes, &names, &directory)?; + Ok((names, directory)) +} + +fn check_directory_digest(header: &[u8], names: &[u8], directory: &[u8]) -> Result<(), String> { + let mut digest = Sha256::new(); + digest.update(names); + digest.update(directory); + if digest.finalize().as_slice() != &header[160..192] { + return Err("KAR directory digest mismatch".into()); + } + Ok(()) +} diff --git a/crates/model-format/src/kar/inspect_file/header.rs b/crates/model-format/src/kar/inspect_file/header.rs new file mode 100644 index 00000000..7e9ec289 --- /dev/null +++ b/crates/model-format/src/kar/inspect_file/header.rs @@ -0,0 +1,133 @@ +//! The 256-byte KAR header: its fields, and the bounded checks that run before any table is read. + +#[allow(unused_imports)] +use super::*; + +/// The header fields `inspect_file` uses once the header checks passed. +pub(super) struct KarHeader { + pub(super) directory_offset: u64, + pub(super) tensor_count: u32, + pub(super) string_offset: u64, + pub(super) string_bytes: u64, + pub(super) payload_offset: u64, + pub(super) archive_bytes: u64, + pub(super) total_elements: u64, + pub(super) payload_bits: u64, + pub(super) source_total_elements: u64, + pub(super) source_bytes: u64, + pub(super) accounted_bpw: f64, + pub(super) source_digest: [u8; 32], + /// `tensor_count * RECORD_BYTES`; a u32 count times 192 cannot overflow u64. + pub(super) directory_bytes: u64, +} + +impl KarHeader { + pub(super) fn parse(header: &[u8], file_bytes: u64) -> Result { + check_identity(header)?; + let parsed = Self::read(header); + parsed.check_sizes(header, file_bytes)?; + parsed.check_offsets()?; + Ok(parsed) + } + + fn read(header: &[u8]) -> Self { + let mut source_digest = [0; 32]; + source_digest.copy_from_slice(&header[128..160]); + let tensor_count = u32_at(header, 32); + Self { + directory_offset: u64_at(header, 24), + tensor_count, + string_offset: u64_at(header, 40), + string_bytes: u64_at(header, 48), + payload_offset: u64_at(header, 56), + archive_bytes: u64_at(header, 64), + total_elements: u64_at(header, 72), + payload_bits: u64_at(header, 80), + source_total_elements: u64_at(header, 88), + source_bytes: u64_at(header, 120), + accounted_bpw: f64::from_le_bytes(header[96..104].try_into().unwrap()), + source_digest, + directory_bytes: tensor_count as u64 * RECORD_BYTES as u64, + } + } + + pub(super) fn summary(&self, max_planes: u8) -> KarSummary { + KarSummary { + archive_bytes: self.archive_bytes, + tensor_count: self.tensor_count, + total_elements: self.total_elements, + source_total_elements: self.source_total_elements, + accounted_bpw: self.accounted_bpw, + source_digest: self.source_digest, + source_bytes: self.source_bytes, + max_planes, + } + } + + fn check_sizes(&self, header: &[u8], file_bytes: u64) -> Result<(), String> { + if self.archive_bytes != file_bytes || self.archive_bytes < HEADER_BYTES as u64 { + return Err("KAR archive length mismatch".into()); + } + if self.tensor_count == 0 || self.tensor_count as usize > MAX_TENSORS || self.string_bytes > MAX_NAMES as u64 { + return Err("KAR metadata exceeds bounded inspector limits".into()); + } + self.check_flags(header)?; + self.check_bits_per_weight() + } + + fn check_flags(&self, header: &[u8]) -> Result<(), String> { + if u32_at(header, 36) != 0 + || header[106] != 1 + || self.total_elements == 0 + || self.total_elements > self.source_total_elements + || self.source_bytes == 0 + { + return Err("invalid KAR flags, digest algorithm, or element counts".into()); + } + Ok(()) + } + + fn check_bits_per_weight(&self) -> Result<(), String> { + let expected = self.archive_bytes as f64 * 8.0 / self.total_elements as f64; + if !self.accounted_bpw.is_finite() || ((self.accounted_bpw - expected) / expected).abs() > 2f64.powi(-40) { + return Err("KAR accounted_bpw does not match archive size".into()); + } + Ok(()) + } + + fn check_offsets(&self) -> Result<(), String> { + let directory_end = self.directory_offset.checked_add(self.directory_bytes).ok_or("KAR directory overflow")?; + let string_end = self.string_offset.checked_add(self.string_bytes).ok_or("KAR string table overflow")?; + if !self.aligned() + || self.directory_offset < HEADER_BYTES as u64 + || directory_end > self.string_offset + || string_end > self.payload_offset + || self.payload_offset > self.archive_bytes + { + return Err("invalid KAR metadata offsets or alignment".into()); + } + Ok(()) + } + + fn aligned(&self) -> bool { + self.directory_offset.is_multiple_of(64) + && self.string_offset.is_multiple_of(64) + && self.payload_offset.is_multiple_of(256) + } +} + +fn check_identity(header: &[u8]) -> Result<(), String> { + if &header[0..8] != b"KARCHIV2" || u32_at(header, 8) != 2 { + return Err("unsupported KAR archive magic or version".into()); + } + if u32_at(header, 12) != 0x04030201 + || u32_at(header, 16) != HEADER_BYTES as u32 + || u32_at(header, 20) != RECORD_BYTES as u32 + { + return Err("invalid KAR byte order or record size".into()); + } + if crc32(&header[..192]) != u32_at(header, 192) { + return Err("KAR header CRC-32 mismatch".into()); + } + Ok(()) +} diff --git a/crates/model-format/src/kar/inspect_file/nested.rs b/crates/model-format/src/kar/inspect_file/nested.rs new file mode 100644 index 00000000..05d78649 --- /dev/null +++ b/crates/model-format/src/kar/inspect_file/nested.rs @@ -0,0 +1,122 @@ +//! The nested (storage class 0) record of the KAR directory: parameters, section layout and coded bits. + +#[allow(unused_imports)] +use super::*; + +/// The group, plane count and padded element count of one nested tensor. +pub(super) struct Nested { + group: u64, + planes: u8, + n_padded: u64, +} + +/// The offsets and sizes a nested record states for the pieces of its section. +#[derive(PartialEq)] +struct Spans { + scales_offset: u64, + scales_bytes: u64, + books_offset: u64, + books_bytes: u64, + planes_offset: u64, + stride: u64, +} + +impl Spans { + fn read(record: &[u8]) -> Self { + Self { + scales_offset: u64_at(record, 64), + scales_bytes: u64_at(record, 72), + books_offset: u64_at(record, 80), + books_bytes: u64_at(record, 88), + planes_offset: u64_at(record, 96), + stride: u32_at(record, 104) as u64, + } + } + + /// Where the pieces must lie for a section that starts at `section_offset`, given the sizes this record states. + fn expected(&self, nested: &Nested, section_offset: u64) -> Result { + let scales_bytes = (nested.n_padded / nested.group).checked_mul(2).ok_or("KAR scale count overflow")?; + let books_bytes = (1u64 << (nested.planes as u32 + 2)) - 4; + let stride = nested.plane_stride()?; + let books_offset = self + .scales_offset + .checked_add(self.scales_bytes) + .and_then(|value| round_up(value, 16)) + .ok_or("KAR books offset overflow")?; + let planes_offset = self + .books_offset + .checked_add(self.books_bytes) + .and_then(|value| round_up(value, 16)) + .ok_or("KAR planes offset overflow")?; + Ok(Self { scales_offset: section_offset, scales_bytes, books_offset, books_bytes, planes_offset, stride }) + } + + fn planes_fit(&self, planes: u8, section_end: u64) -> bool { + self.planes_offset.checked_add(planes as u64 * self.stride).is_some_and(|end| end <= section_end) + } +} + +impl Nested { + pub(super) fn read(record: &[u8], n_elements: u64) -> Result { + let group = u16_at(record, 46) as u64; + let planes = record[42]; + let n_padded = u64_at(record, 56); + if !valid_parameters(record, group, planes) { + return Err("invalid KAR nested tensor parameters".into()); + } + let rounded = n_elements.div_ceil(group).checked_mul(group).ok_or("KAR padded count overflow")?; + if n_padded != rounded { + return Err("KAR padded tensor count mismatch".into()); + } + Ok(Self { group, planes, n_padded }) + } + + fn plane_stride(&self) -> Result { + let plane_words_bytes = (self.n_padded / 32).checked_mul(4).ok_or("KAR plane size overflow")?; + round_up(plane_words_bytes, 16).ok_or_else(|| "KAR plane stride overflow".to_owned()) + } + + pub(super) fn check_layout(&self, record: &[u8], section_offset: u64, section_end: u64) -> Result<(), String> { + let actual = Spans::read(record); + let expected = actual.expected(self, section_offset)?; + if actual != expected || !actual.planes_fit(self.planes, section_end) { + return Err("invalid KAR nested tensor section layout".into()); + } + Ok(()) + } + + pub(super) fn coded_bits(&self) -> Result { + let scale_bits = (self.n_padded / self.group).checked_mul(16); + (self.planes as u64) + .checked_mul(self.n_padded) + .and_then(|bits| scale_bits.and_then(|scale_bits| bits.checked_add(scale_bits))) + .ok_or_else(|| "KAR tensor bit count overflow".to_owned()) + } +} + +fn valid_parameters(record: &[u8], group: u64, planes: u8) -> bool { + group != 0 + && group <= 1024 + && group.is_multiple_of(32) + && (1..=16).contains(&planes) + && record[43] != 0 + && record[43] <= record[44] + && record[44] <= planes + && record[45] <= 1 +} + +/// The checks of a raw (storage class 1) record. +pub(super) fn check_raw(record: &[u8], n_elements: u64) -> Result<(), String> { + if record[42..48].iter().any(|value| *value != 0) + || u64_at(record, 56) != n_elements + || record[64..104].iter().any(|value| *value != 0) + || u32_at(record, 104) != 0 + { + return Err("invalid KAR raw tensor metadata".into()); + } + let width = if record[41] == 0 { 4 } else { 2 }; + if u64_at(record, 120) < n_elements.checked_mul(width).ok_or("KAR raw tensor size overflow")? { + return Err("KAR raw tensor section is too small".into()); + } + Ok(()) +} diff --git a/crates/model-format/src/kar/inspect_file/records.rs b/crates/model-format/src/kar/inspect_file/records.rs new file mode 100644 index 00000000..b9429435 --- /dev/null +++ b/crates/model-format/src/kar/inspect_file/records.rs @@ -0,0 +1,145 @@ +//! The directory records of a KAR archive, checked one by one against the header totals. + +#[allow(unused_imports)] +use super::*; + +use super::nested::{Nested, check_raw}; + +/// The running totals of the record loop; `finish` compares them with the header. +pub(super) struct RecordScan<'a> { + seen_names: HashSet<&'a str>, + elements_sum: u64, + bits_sum: u64, + previous_end: u64, + min_planes: u8, + pub(super) max_planes: u8, + pub(super) sections: Vec
, + pub(super) sources: Vec, +} + +impl<'a> RecordScan<'a> { + pub(super) fn new(header: &KarHeader) -> Result { + let count = header.tensor_count as usize; + let mut seen_names = HashSet::new(); + seen_names.try_reserve(count).map_err(|_| "KAR allocation failed")?; + let mut sections = Vec::new(); + sections.try_reserve_exact(count).map_err(|_| "KAR allocation failed")?; + let mut sources = Vec::new(); + sources.try_reserve_exact(count).map_err(|_| "KAR allocation failed")?; + Ok(Self { + seen_names, + elements_sum: 0, + bits_sum: 0, + previous_end: header.payload_offset, + min_planes: u8::MAX, + max_planes: 0, + sections, + sources, + }) + } + + pub(super) fn record(&mut self, header: &KarHeader, names: &'a [u8], record: &[u8]) -> Result<(), String> { + let name = self.unique_name(names, record)?; + let dims = record_dims(record)?; + let n_elements = element_count(record, &dims)?; + self.elements_sum = self.elements_sum.checked_add(n_elements).ok_or("KAR model element count overflow")?; + self.sources.push(tensor_source(name, &dims, record, n_elements)); + let section_end = self.add_section(header, record)?; + if record[7] == 0 { self.nested(record, n_elements, section_end) } else { check_raw(record, n_elements) } + } + + pub(super) fn finish(&self, header: &KarHeader, header_bytes: &[u8]) -> Result<(), String> { + let min_planes = if self.min_planes == u8::MAX { 0 } else { self.min_planes }; + if self.previous_end != header.archive_bytes + || self.elements_sum != header.total_elements + || self.bits_sum != header.payload_bits + || header_bytes[104] != min_planes + || header_bytes[105] != self.max_planes + { + return Err("KAR aggregate metadata mismatch".into()); + } + Ok(()) + } + + fn unique_name(&mut self, names: &'a [u8], record: &[u8]) -> Result<&'a str, String> { + let name_start = u32_at(record, 0) as usize; + let name_len = u16_at(record, 4) as usize; + let name_end = name_start.checked_add(name_len).ok_or("KAR name offset overflow")?; + if name_end >= names.len() || names[name_end] != 0 { + return Err("invalid KAR tensor name bounds".into()); + } + let name = std::str::from_utf8(&names[name_start..name_end]).map_err(|_| "KAR tensor name is not UTF-8")?; + if !self.seen_names.insert(name) { + return Err("duplicate KAR tensor name".into()); + } + Ok(name) + } + + /// Checks that the section follows the previous one and lies inside the archive; returns its end. + fn add_section(&mut self, header: &KarHeader, record: &[u8]) -> Result { + let section_offset = u64_at(record, 112); + let section_bytes = u64_at(record, 120); + let section_end = section_offset.checked_add(section_bytes).ok_or("KAR tensor section overflow")?; + if section_offset != self.previous_end + || !section_offset.is_multiple_of(256) + || section_end > header.archive_bytes + { + return Err("KAR tensor sections are not contiguous or bounded".into()); + } + self.previous_end = section_end; + self.sections.push(Section { offset: section_offset, bytes: section_bytes, crc32: u32_at(record, 108) }); + Ok(section_end) + } + + fn nested(&mut self, record: &[u8], n_elements: u64, section_end: u64) -> Result<(), String> { + let nested = Nested::read(record, n_elements)?; + nested.check_layout(record, u64_at(record, 112), section_end)?; + self.bits_sum = self.bits_sum.checked_add(nested.coded_bits()?).ok_or("KAR coded bit count overflow")?; + self.min_planes = self.min_planes.min(record[43]); + self.max_planes = self.max_planes.max(record[44]); + Ok(()) + } +} + +/// The dimensions of a record (as many as it declares) after the layout and unused-dimension checks. +fn record_dims(record: &[u8]) -> Result, String> { + let n_dims = record[6] as usize; + if !(1..=4).contains(&n_dims) || record[7] > 1 || record[40] != 0 || record[41] > 2 { + return Err("unsupported KAR tensor layout".into()); + } + let mut dims = (0..4).map(|index| u64_at(record, 8 + index * 8)).collect::>(); + if dims[n_dims..].iter().any(|dim| *dim != 1) { + return Err("invalid KAR unused dimension".into()); + } + dims.truncate(n_dims); + Ok(dims) +} + +fn element_count(record: &[u8], dims: &[u64]) -> Result { + let product = dims.iter().try_fold(1u64, |acc, dim| acc.checked_mul(*dim)).ok_or("KAR tensor shape overflow")?; + let n_elements = u64_at(record, 48); + if product != n_elements || n_elements == 0 { + return Err("KAR tensor element count mismatch".into()); + } + Ok(n_elements) +} + +fn tensor_source(name: &str, dims: &[u64], record: &[u8], n_elements: u64) -> KarTensorSource { + let mut digest = [0u8; 32]; + digest.copy_from_slice(&record[128..160]); + KarTensorSource { + name: name.to_owned(), + dimensions: dims.to_vec(), + dtype: record[41], + digest, + offset: u64_at(record, 160), + section_bytes: u64_at(record, 120), + storage_class: record[7], + n_elements, + planes_min: record[43], + planes_max: record[44], + section_offset: u64_at(record, 112), + planes_offset: u64_at(record, 96), + plane_stride_bytes: u32_at(record, 104), + } +} diff --git a/crates/model-format/src/kar/read_region.rs b/crates/model-format/src/kar/read_region.rs index 25e424a8..cc52c9c1 100644 --- a/crates/model-format/src/kar/read_region.rs +++ b/crates/model-format/src/kar/read_region.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: fn read_region, fn u16_at, fn u32_at, fn u64_at, fn crc32, fn crc32_step .... +//! Moved out of the parent module by STRA-338: fn read_region, fn u16_at, fn u32_at, fn u64_at, fn crc32, fn crc32_step +//! .... #[allow(unused_imports)] use super::*; @@ -66,6 +67,54 @@ pub(super) fn integrity_sections(sections: &[Section], bytes: u64) -> Result<(), Ok(()) } +/// The per-section CRC-32 state of an archive that is fed chunk by chunk, in order. +pub(super) struct SectionCrc<'a> { + sections: &'a [Section], + index: usize, + total: u64, + crc: u32, + failed: bool, +} + +impl<'a> SectionCrc<'a> { + fn new(sections: &'a [Section]) -> Self { + Self { sections, index: 0, total: 0, crc: !0u32, failed: false } + } + + fn feed(&mut self, chunk: &[u8]) { + let end = self.total + chunk.len() as u64; + while let Some(section) = self.sections.get(self.index) { + if section.offset >= end { + break; + } + let section_end = section.offset + section.bytes; // Checked by integrity_sections. + let start = self.total.max(section.offset); + let stop = end.min(section_end); + self.crc = crc32_step(self.crc, &chunk[(start - self.total) as usize..(stop - self.total) as usize]); + if stop != section_end { + break; + } + self.failed |= !self.crc != section.crc32; + self.crc = !0u32; + self.index += 1; + } + self.total = end; + } +} + +/// SHA first, then CRC: a CRC failure never shortcuts the full hash or changes SHA-first precedence. +fn integrity_verdict(total: u64, digest: Sha256, crc: &SectionCrc, bytes: u64, pin: &[u8; 32]) -> Result<(), KarError> { + if total != bytes || digest.finalize().as_slice() != pin { + return Err(KarError::Integrity("KAR full archive SHA-256 mismatch")); + } + if crc.failed || crc.index != crc.sections.len() { + return Err(KarError::Integrity("KAR payload CRC-32 mismatch")); + } + Ok(()) +} + +type ChunkReceiver = std::sync::mpsc::Receiver>>; + /// The production form of [`verify_integrity_stream`]: one reader thread keeps chunks coming, SHA-256 of the /// whole archive runs on the calling thread and the per-section CRC-32 on a second one, so the pass costs the /// slower of the two instead of the read plus both. Same verdicts, same precedence: a SHA mismatch (or a short @@ -77,64 +126,49 @@ pub(super) fn verify_integrity_pipelined( pin: &[u8; 32], ) -> Result<(), KarError> { integrity_sections(sections, bytes)?; - let (digest, total, crc) = crate::readahead::with_read_ahead(file, 0, bytes, 2, |mut receivers| { - let crc_rx = receivers.pop().expect("two receivers"); - let sha_rx = receivers.pop().expect("two receivers"); - std::thread::scope(|scope| { - let crc_thread = scope.spawn(move || -> std::io::Result<(bool, usize)> { - let (mut index, mut total, mut crc, mut failed) = (0usize, 0u64, !0u32, false); - for item in crc_rx { - let chunk = item?; - let end = total + chunk.len() as u64; - while let Some(section) = sections.get(index) { - if section.offset >= end { - break; - } - let section_end = section.offset + section.bytes; // Checked by integrity_sections. - let start = total.max(section.offset); - let stop = end.min(section_end); - crc = crc32_step(crc, &chunk[(start - total) as usize..(stop - total) as usize]); - if stop != section_end { - break; - } - failed |= !crc != section.crc32; - crc = !0u32; - index += 1; - } - total = end; - } - Ok((failed, index)) - }); - let mut digest = Sha256::new(); - let mut total = 0u64; - let mut read_error = None; - for item in sha_rx { - match item { - Ok(chunk) => { - digest.update(&chunk[..]); - total += chunk.len() as u64; - } - Err(error) => { - read_error = Some(error); - break; - } - } + let (digest, total, crc) = + crate::readahead::with_read_ahead(file, 0, bytes, 2, |receivers| hash_and_crc(receivers, sections))?; + integrity_verdict(total, digest, &crc, bytes, pin) +} + +/// SHA-256 on this thread and the section CRCs on a second one, over the two receivers of one read-ahead. +fn hash_and_crc<'a>( + mut receivers: Vec, + sections: &'a [Section], +) -> Result<(Sha256, u64, SectionCrc<'a>), KarError> { + let crc_rx = receivers.pop().expect("two receivers"); + let sha_rx = receivers.pop().expect("two receivers"); + std::thread::scope(|scope| { + let crc_thread = scope.spawn(move || -> std::io::Result> { + let mut crc = SectionCrc::new(sections); + for item in crc_rx { + crc.feed(&item?[..]); } - let crc = crc_thread.join().expect("the CRC thread does not panic"); - match read_error { - Some(error) => Err(KarError::Io(error)), - None => crc.map(|c| (digest, total, c)).map_err(KarError::Io), + Ok(crc) + }); + let (digest, total, read_error) = hash_chunks(sha_rx); + let crc = crc_thread.join().expect("the CRC thread does not panic"); + match read_error { + Some(error) => Err(KarError::Io(error)), + None => crc.map(|c| (digest, total, c)).map_err(KarError::Io), + } + }) +} + +/// SHA-256 and byte count of the chunks up to the first read error (returned with them). +fn hash_chunks(receiver: ChunkReceiver) -> (Sha256, u64, Option) { + let mut digest = Sha256::new(); + let mut total = 0u64; + for item in receiver { + match item { + Ok(chunk) => { + digest.update(&chunk[..]); + total += chunk.len() as u64; } - }) - })?; - let (crc_failed, index) = crc; - if total != bytes || digest.finalize().as_slice() != pin { - return Err(KarError::Integrity("KAR full archive SHA-256 mismatch")); + Err(error) => return (digest, total, Some(error)), + } } - if crc_failed || index != sections.len() { - return Err(KarError::Integrity("KAR payload CRC-32 mismatch")); - } - Ok(()) + (digest, total, None) } /// The reference scan (kept for the tests that pin its verdicts; production uses the pipelined form above). @@ -151,42 +185,19 @@ pub(super) fn verify_integrity_stream( return Err(KarError::Range("KAR integrity buffer is empty")); } let mut digest = Sha256::new(); - let mut total = 0u64; - let mut index = 0; - let mut crc = !0u32; - let mut crc_failed = false; + let mut crc = SectionCrc::new(sections); loop { let n = file.read(buffer).map_err(KarError::Io)?; if n == 0 { break; } - let end = total.checked_add(n as u64).ok_or(KarError::Range("KAR hash length overflow"))?; - digest.update(&buffer[..n]); // Metadata and padding belong to the SHA too. - while let Some(section) = sections.get(index) { - if section.offset >= end { - break; - } - let section_end = section.offset + section.bytes; // Checked above. - let start = total.max(section.offset); - let stop = end.min(section_end); - crc = crc32_step(crc, &buffer[(start - total) as usize..(stop - total) as usize]); - if stop != section_end { - break; - } - crc_failed |= !crc != section.crc32; - crc = !0u32; - index += 1; + if crc.total.checked_add(n as u64).is_none() { + return Err(KarError::Range("KAR hash length overflow")); } - total = end; + digest.update(&buffer[..n]); // Metadata and padding belong to the SHA too. + crc.feed(&buffer[..n]); } - // A CRC failure never shortcuts the full hash or changes SHA-first precedence. - if total != bytes || digest.finalize().as_slice() != pin { - return Err(KarError::Integrity("KAR full archive SHA-256 mismatch")); - } - if crc_failed || index != sections.len() { - return Err(KarError::Integrity("KAR payload CRC-32 mismatch")); - } - Ok(()) + integrity_verdict(crc.total, digest, &crc, bytes, pin) } pub(super) fn round_up(value: u64, alignment: u64) -> Option { diff --git a/crates/model-format/src/kar/row_read_tests.rs b/crates/model-format/src/kar/row_read_tests.rs new file mode 100644 index 00000000..da33a1c5 --- /dev/null +++ b/crates/model-format/src/kar/row_read_tests.rs @@ -0,0 +1,175 @@ +//! Row-read tests of the PLE archive: the warm single-thread path against the parallel packets, the file-state guard. + +use super::*; +use std::io::Write; +use std::sync::atomic::Ordering; + +/// Two partitions over one synthetic file; every byte is below 0x70 so no scale reads as non-finite. +fn synthetic() -> (File, Vec, u64, std::path::PathBuf) { + let (n0, n1) = (1000u64, 500u64); + let scales0 = 0u64; + let planes0 = scales0 + n0 * 10; + let stride0 = n0 * 20; + let scales1 = planes0 + 2 * stride0; + let planes1 = scales1 + n1 * 10; + let stride1 = n1 * 20; + let total = planes1 + 2 * stride1; + let mut x = 0x9E37_79B9_7F4A_7C15u64; + let bytes: Vec = (0..total) + .map(|_| { + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + (x % 0x70) as u8 + }) + .collect(); + // one file per call: the tests run in parallel and several of them touch, chmod or remove theirs + static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + let unique = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let path = std::env::temp_dir().join(format!("leleka-kar-rows-{}-{:x}-{unique}", std::process::id(), x)); + File::create(&path).unwrap().write_all(&bytes).unwrap(); + let parts = vec![ + VerifiedPart { row_base: 0, row_count: n0, scales: scales0, planes: planes0, stride: stride0 }, + VerifiedPart { row_base: n0, row_count: n1, scales: scales1, planes: planes1, stride: stride1 }, + ]; + (File::open(&path).unwrap(), parts, total, path) +} + +fn same(a: &[KarPleRowPacket], b: &[KarPleRowPacket]) -> bool { + a.len() == b.len() && a.iter().zip(b).all(|(x, y)| x.payload == y.payload && x.partition == y.partition) +} + +#[test] +fn the_warm_single_thread_read_returns_exactly_the_parallel_packets() { + let (file, parts, total, path) = synthetic(); + let files = vec![file.try_clone().unwrap(), file.try_clone().unwrap(), file.try_clone().unwrap()]; + let mut x = 7u64; + for case in 0..40 { + let rows: Vec = (0..16) + .map(|_| { + x = x.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + (x >> 33) % 1500 + }) + .collect(); + // the reference: one thread, no probe + let mut reference = vec![KarPleRowPacket { payload: [0; 50], partition: 0 }; 16]; + read_rows_chunk(&file, &parts, &rows, &mut reference).unwrap(); + check_probe_paths(&files, (&parts, total), &rows, &reference, case); + } + COLD_SKIP.store(0, Ordering::Relaxed); + check_refusals(&files, &parts, total); + drop(files); + let _ = std::fs::remove_file(path); +} + +/// The packets are the same on every path: probed, parallel after a cold verdict, and without a probe. +fn check_probe_paths( + files: &[File], + (parts, total): (&[VerifiedPart], u64), + rows: &[u64], + reference: &[KarPleRowPacket], + case: usize, +) { + // the file is in the page cache: the probe takes the single-thread path (or, on a loaded machine, falls + // back to threads; the packets are the same either way) + COLD_SKIP.store(0, Ordering::Relaxed); + let probed = read_rows_parallel(files, parts, total, None, rows, 8, 2, true).unwrap(); + assert!(same(&probed, reference), "case {case}: probing read"); + // after a cold verdict the next calls skip the probe and read in parallel + COLD_SKIP.store(3, Ordering::Relaxed); + let parallel = read_rows_parallel(files, parts, total, None, rows, 8, 2, true).unwrap(); + assert!(same(¶llel, reference), "case {case}: parallel read after a cold verdict"); + assert_eq!(COLD_SKIP.load(Ordering::Relaxed), 2, "a skipped probe uses up one of the skip calls"); + let unprobed = read_rows_parallel(files, parts, total, None, rows, 8, 2, false).unwrap(); + assert!(same(&unprobed, reference), "case {case}: no probe"); +} + +/// The refusals are the same as before: a row outside the table, a changed archive length. +fn check_refusals(files: &[File], parts: &[VerifiedPart], total: u64) { + let bad = vec![PLE_ROWS; 16]; + assert!(matches!(read_rows_parallel(files, parts, total, None, &bad, 8, 2, true), Err(KarError::Range(_)))); + assert!(matches!( + read_rows_parallel(files, parts, total + 1, None, &[1, 2], 8, 2, true), + Err(KarError::Integrity(_)) + )); + // a row beyond the partitions' last row is a range error on the probe path as well + let beyond: Vec = (0..16).map(|i| 1500 + i).collect(); + assert!(read_rows_parallel(files, parts, total, None, &beyond, 8, 2, true).is_err()); +} + +#[cfg(unix)] +#[test] +fn an_ordinary_archive_file_must_still_be_in_the_state_that_was_verified() { + let (file, parts, total, path) = synthetic(); + let id = crate::verify_stamp::FileIdentity::of(&file.metadata().unwrap()).unwrap(); + let files = vec![file.try_clone().unwrap()]; + let rows: Vec = vec![3, 999, 1000, 1400]; + let ok = read_rows_parallel(&files, &parts, total, Some(&id), &rows, 8, 2, false).unwrap(); + let reference = read_rows_parallel(&files, &parts, total, None, &rows, 8, 2, false).unwrap(); + assert!(same(&ok, &reference), "the check changes no byte that is returned"); + // a sealed memfd has no identity to compare: the length check alone + assert!(check_archive_state(&file, total, None).is_ok()); + assert!( + matches!(check_archive_state(&file, total + 1, Some(&id)), Err(KarError::Integrity(m)) if m.contains("length")) + ); + let id2 = check_touched_file(&file, &files, (&parts, total), &rows, &path, &id); + check_chmod_and_reader(&file, files, (parts, total), (&rows, &path), (id2, &reference)); + let _ = std::fs::remove_file(path); +} + +/// The file is touched (mtime and ctime move, size and bytes do not): refused, on every entry point; the new state is +/// a new identity: verifying again (and stamping) is how the service goes on. Returns the new identity. +#[cfg(unix)] +fn check_touched_file( + file: &File, + files: &[File], + (parts, total): (&[VerifiedPart], u64), + rows: &[u64], + path: &std::path::Path, + id: &crate::verify_stamp::FileIdentity, +) -> crate::verify_stamp::FileIdentity { + std::thread::sleep(std::time::Duration::from_millis(30)); + let handle = std::fs::OpenOptions::new().write(true).open(path).unwrap(); + handle.set_modified(std::time::SystemTime::now()).unwrap(); + drop(handle); + let refused = read_rows_parallel(files, parts, total, Some(id), rows, 8, 2, false); + assert!(matches!(refused, Err(KarError::Integrity(m)) if m.contains("changed since it was verified"))); + assert!(matches!(check_archive_state(file, total, Some(id)), Err(KarError::Integrity(_)))); + let id2 = crate::verify_stamp::FileIdentity::of(&file.metadata().unwrap()).unwrap(); + assert_ne!(*id, id2); + assert!(read_rows_parallel(files, parts, total, Some(&id2), rows, 8, 2, false).is_ok()); + id2 +} + +/// chmod alone moves ctime and is refused too; the reader a prefill thread owns carries the same state. +#[cfg(unix)] +fn check_chmod_and_reader( + file: &File, + files: Vec, + (parts, total): (Vec, u64), + (rows, path): (&[u64], &std::path::Path), + (id2, reference): (crate::verify_stamp::FileIdentity, &[KarPleRowPacket]), +) { + use std::os::unix::fs::PermissionsExt; + std::thread::sleep(std::time::Duration::from_millis(30)); + std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o400)).unwrap(); + assert!(matches!(check_archive_state(file, total, Some(&id2)), Err(KarError::Integrity(_)))); + let reader = KarPleRowReader { + files: vec![file.try_clone().unwrap()], + parts: parts.clone(), + archive_bytes: total, + identity: Some(id2), + }; + assert!(matches!(reader.read_rows(rows, 4), Err(KarError::Integrity(_)))); + let reader = KarPleRowReader { files, parts, archive_bytes: total, identity: None }; + assert!(same(&reader.read_rows(rows, 4).unwrap(), reference)); +} +#[test] +fn the_startup_figures_add_up() { + let read = KarStartupRead { trust: KarTrust::Stamp, metadata_bytes: 1_000, book_bytes: 16, hashed_bytes: 0 }; + assert_eq!(read.total_bytes(), 1_016); + assert_eq!(read.trust.as_str(), "stamp"); + let full = KarStartupRead { trust: KarTrust::FullPass, hashed_bytes: 55_295_529_472, ..read }; + assert_eq!(full.total_bytes(), 55_295_529_472 + 1_016); + assert_eq!((KarTrust::AttestedMemfd.as_str(), KarTrust::FullPass.as_str()), ("attested-memfd", "full-pass")); +} diff --git a/crates/model-format/src/kar_extents.rs b/crates/model-format/src/kar_extents.rs index 872b4fca..b5c6d04a 100644 --- a/crates/model-format/src/kar_extents.rs +++ b/crates/model-format/src/kar_extents.rs @@ -14,7 +14,9 @@ //! bytes of the extents, in order; //! * [`KarCensus`] is the read-only report `examples/kar_census.rs` prints. -use super::{KarError, KarInspection, KarNestedRecord, PLE_ROWS, Sha256, VerifiedPart, read_at, round_up}; +use super::{ + KarError, KarInspection, KarNestedRecord, KarTensorSource, PLE_ROWS, Sha256, VerifiedPart, read_at, round_up, +}; use sha2::Digest; use std::fmt::Write as _; @@ -31,10 +33,13 @@ pub const PLE_ROW_PLANE_BYTES: u64 = 20; /// Planes the serve path reads (level 2). pub const PLE_PLANES: u64 = 2; -/// SHA-256 of the extents of the pinned archive (see [`digest_extents_with`]): 2 extents, 16,000,348,672 bytes, measured on the -/// real archive file on the 5090 server (2026-11-02, `kar_census ARCHIVE --hash-extents`, 161.9 s at <= 300 MiB/s) -- the file +/// SHA-256 of the extents of the pinned archive (see [`digest_extents_with`]): 2 extents, 16,000,348,672 bytes, +/// measured on the +/// real archive file on the 5090 server (2026-11-02, `kar_census ARCHIVE --hash-extents`, 161.9 s at <= 300 MiB/s) -- +/// the file /// that every holder job copies and whose full SHA-256 the engine checks on each of those copies. Hex: -/// 7568b1211419a7c10a9b39a86230f75b7fa9c02839e36c9b5f2494ec7af72143. While it is all zero a sparse copy is refused unless the +/// 7568b1211419a7c10a9b39a86230f75b7fa9c02839e36c9b5f2494ec7af72143. While it is all zero a sparse copy is refused +/// unless the /// operator supplies the digest explicitly. pub const PLE_EXTENTS_SHA256: [u8; 32] = [ 117, 104, 177, 33, 20, 25, 167, 193, 10, 155, 57, 168, 98, 48, 247, 91, 127, 169, 192, 40, 57, 227, 108, 155, 95, diff --git a/crates/model-format/src/kar_extents/impl_extent.rs b/crates/model-format/src/kar_extents/impl_extent.rs index 187085a8..60ddeda9 100644 --- a/crates/model-format/src/kar_extents/impl_extent.rs +++ b/crates/model-format/src/kar_extents/impl_extent.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: impl Extent, fn extents_bytes, fn normalize_extents, fn extents_cover, fn extents_overlap, fn digest_extents_with .... +//! Moved out of the parent module by STRA-338: impl Extent, fn extents_bytes, fn normalize_extents, fn extents_cover, +//! fn extents_overlap, fn digest_extents_with .... #[allow(unused_imports)] use super::*; diff --git a/crates/model-format/src/kar_extents/impl_karinspection.rs b/crates/model-format/src/kar_extents/impl_karinspection.rs index 734d638e..88b7dfbd 100644 --- a/crates/model-format/src/kar_extents/impl_karinspection.rs +++ b/crates/model-format/src/kar_extents/impl_karinspection.rs @@ -42,28 +42,7 @@ impl KarInspection { pub fn census(&self, part_names: &[&str]) -> Result { let serve = self.serve_reads(part_names)?; let nested = self.nested_records()?; - let mut records = Vec::with_capacity(self.sources.len()); - for source in &self.sources { - let ple = serve.parts.iter().find(|p| p.name == source.name); - let stored = nested.iter().find(|n| n.name == source.name).map(|n| n.planes_stored); - let class = match (ple.is_some(), source.storage_class) { - (true, _) => RecordClass::PleRows, - (false, 0) => RecordClass::NestedUnread, - (false, _) => RecordClass::RawUnread, - }; - let section = Extent::new(source.section_offset, source.section_bytes); - records.push(CensusRecord { - name: source.name.clone(), - class, - dimensions: source.dimensions.clone(), - dtype: source.dtype, - n_elements: source.n_elements, - planes_stored: stored, - section, - exact_read_bytes: extents_overlap(&serve.exact, section.offset, section.len), - extent_bytes: extents_overlap(&serve.extents, section.offset, section.len), - }); - } + let records = self.sources.iter().map(|source| census_record(source, &serve, &nested)).collect(); Ok(KarCensus { archive_bytes: self.summary.archive_bytes, payload_offset: self.payload_offset, @@ -74,6 +53,29 @@ impl KarInspection { } } +/// The census line of one directory record. +fn census_record(source: &KarTensorSource, serve: &ServeReads, nested: &[KarNestedRecord]) -> CensusRecord { + let ple = serve.parts.iter().find(|p| p.name == source.name); + let stored = nested.iter().find(|n| n.name == source.name).map(|n| n.planes_stored); + let class = match (ple.is_some(), source.storage_class) { + (true, _) => RecordClass::PleRows, + (false, 0) => RecordClass::NestedUnread, + (false, _) => RecordClass::RawUnread, + }; + let section = Extent::new(source.section_offset, source.section_bytes); + CensusRecord { + name: source.name.clone(), + class, + dimensions: source.dimensions.clone(), + dtype: source.dtype, + n_elements: source.n_elements, + planes_stored: stored, + section, + exact_read_bytes: extents_overlap(&serve.exact, section.offset, section.len), + extent_bytes: extents_overlap(&serve.extents, section.offset, section.len), + } +} + impl RecordClass { pub fn label(self) -> &'static str { match self { @@ -104,8 +106,6 @@ impl KarCensus { /// Render the report. `all_records` lists every record (otherwise only the totals and the PLE partitions). pub fn render(&self, all_records: bool) -> String { - let gib = |b: u64| b as f64 / (1u64 << 30) as f64; - let pct = |part: u64, whole: u64| 100.0 * part as f64 / whole.max(1) as f64; let mut out = String::new(); let _ = writeln!(out, "archive_bytes={}", self.archive_bytes); let _ = writeln!(out, "tensor_records={}", self.records.len()); @@ -115,34 +115,54 @@ impl KarCensus { self.payload_offset, self.payload_offset, self.metadata_extent_bytes ); if all_records { + self.render_all_records(&mut out); + } else { + self.render_ple_records(&mut out); + } + self.render_totals(&mut out); + self.render_serve_reads(&mut out); + self.render_unread(&mut out); + let _ = writeln!(out, "ple_rows_expected={PLE_ROWS}"); + let _ = writeln!(out, "ple_rows_found={}", self.serve.parts.iter().map(|p| p.rows).sum::()); + out + } + + fn render_all_records(&self, out: &mut String) { + let _ = writeln!( + out, + concat!( + "\n# index class section_offset section_bytes elements planes read_exact ", + "in_sparse_copy name dims" + ) + ); + for (i, r) in self.records.iter().enumerate() { let _ = writeln!( out, - "\n# index class section_offset section_bytes elements planes read_exact in_sparse_copy name dims" + "{i:>5} {:<20} {:>16} {:>15} {:>14} {:>6} {:>12} {:>14} {} {:?}", + r.class.label(), + r.section.offset, + r.section.len, + r.n_elements, + r.planes_stored.map_or("raw".to_owned(), |p| p.to_string()), + r.exact_read_bytes, + r.extent_bytes, + r.name, + r.dimensions ); - for (i, r) in self.records.iter().enumerate() { - let _ = writeln!( - out, - "{i:>5} {:<20} {:>16} {:>15} {:>14} {:>6} {:>12} {:>14} {} {:?}", - r.class.label(), - r.section.offset, - r.section.len, - r.n_elements, - r.planes_stored.map_or("raw".to_owned(), |p| p.to_string()), - r.exact_read_bytes, - r.extent_bytes, - r.name, - r.dimensions - ); - } - } else { - for (i, r) in self.records.iter().enumerate().filter(|(_, r)| r.class == RecordClass::PleRows) { - let _ = writeln!( - out, - "ple record {i}: {} section [{}, +{}) read_exact={} in_sparse_copy={}", - r.name, r.section.offset, r.section.len, r.exact_read_bytes, r.extent_bytes - ); - } } + } + + fn render_ple_records(&self, out: &mut String) { + for (i, r) in self.records.iter().enumerate().filter(|(_, r)| r.class == RecordClass::PleRows) { + let _ = writeln!( + out, + "ple record {i}: {} section [{}, +{}) read_exact={} in_sparse_copy={}", + r.name, r.section.offset, r.section.len, r.exact_read_bytes, r.extent_bytes + ); + } + } + + fn render_totals(&self, out: &mut String) { let _ = writeln!(out, "\n# totals per kind"); let _ = writeln!( out, @@ -161,22 +181,11 @@ impl KarCensus { t.extent_bytes ); } + } + + fn render_serve_reads(&self, out: &mut String) { let _ = writeln!(out, "\n# serve path reads (derived from the same geometry as read_rows_chunk)"); - for p in &self.serve.parts { - let _ = writeln!( - out, - "part {}: rows={} scales=[{}, +{}) plane0=[{}, +{}) plane1=[{}, +{}) book=[{}, +8)", - p.name, - p.rows, - p.scales.offset, - p.scales.len, - p.planes[0].offset, - p.planes[0].len, - p.planes[1].offset, - p.planes[1].len, - p.book.offset - ); - } + self.render_parts(out); let exact = self.serve.exact_bytes(); let ext = self.serve.extent_bytes(); let _ = writeln!( @@ -192,6 +201,27 @@ impl KarCensus { pct(ext, self.archive_bytes), self.serve.extents.len() ); + } + + fn render_parts(&self, out: &mut String) { + for p in &self.serve.parts { + let _ = writeln!( + out, + "part {}: rows={} scales=[{}, +{}) plane0=[{}, +{}) plane1=[{}, +{}) book=[{}, +8)", + p.name, + p.rows, + p.scales.offset, + p.scales.len, + p.planes[0].offset, + p.planes[0].len, + p.planes[1].offset, + p.planes[1].len, + p.book.offset + ); + } + } + + fn render_unread(&self, out: &mut String) { let unread = self.unread_extent_bytes(); let _ = writeln!( out, @@ -216,8 +246,13 @@ impl KarCensus { pct(first.section.offset, self.archive_bytes) ); } - let _ = writeln!(out, "ple_rows_expected={PLE_ROWS}"); - let _ = writeln!(out, "ple_rows_found={}", self.serve.parts.iter().map(|p| p.rows).sum::()); - out } } + +fn gib(bytes: u64) -> f64 { + bytes as f64 / (1u64 << 30) as f64 +} + +fn pct(part: u64, whole: u64) -> f64 { + 100.0 * part as f64 / whole.max(1) as f64 +} diff --git a/crates/model-format/src/kar_kernel_model/decode_params_valid.rs b/crates/model-format/src/kar_kernel_model/decode_params_valid.rs index 8a18976f..f1696bed 100644 --- a/crates/model-format/src/kar_kernel_model/decode_params_valid.rs +++ b/crates/model-format/src/kar_kernel_model/decode_params_valid.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: fn decode_params_valid, fn decode_grid, fn kernel_decode, fn kernel_multiply, fn kernel_swiglu, fn stage_packet. +//! Moved out of the parent module by STRA-338: fn decode_params_valid, fn decode_grid, fn kernel_decode, fn +//! kernel_multiply, fn kernel_swiglu, fn stage_packet. #[allow(unused_imports)] use super::*; @@ -7,28 +8,37 @@ use super::*; /// 64-bit arithmetic before any packet byte is read, so a corrupt parameter /// block cannot cause an out-of-bounds device read. pub fn decode_params_valid(p: &DecodeParams) -> bool { + level_and_count_ok(p) && group_ok(p) && layout_ok(p) && regions_fit(p) +} + +fn level_and_count_ok(p: &DecodeParams) -> bool { + let level = u64::from(p.level); + let count = u64::from(p.count); + (u64::from(MIN_LEVEL)..=u64::from(MAX_LEVEL)).contains(&level) + && level <= u64::from(p.staged_planes) + && count != 0 + && count <= MAX_RANGE_ELEMENTS +} + +fn group_ok(p: &DecodeParams) -> bool { + let group = u64::from(p.group); + group != 0 && group <= 1024 && group.is_multiple_of(32) && p.head32 < 32 && u64::from(p.head_group) < group +} + +fn layout_ok(p: &DecodeParams) -> bool { + p.scales_offset.is_multiple_of(2) + && p.planes_offset.is_multiple_of(4) + && p.plane_stride_words.is_multiple_of(4) + && p.window_words <= p.plane_stride_words + && u64::from(p.packet_bytes) >= BOOK_REGION_BYTES +} + +/// Every staged word / group the loop can touch exists, and every region +/// lies inside the packet. Only called once the level, count and group are valid. +fn regions_fit(p: &DecodeParams) -> bool { let level = u64::from(p.level); let count = u64::from(p.count); let group = u64::from(p.group); - if !(u64::from(MIN_LEVEL)..=u64::from(MAX_LEVEL)).contains(&level) - || level > u64::from(p.staged_planes) - || count == 0 - || count > MAX_RANGE_ELEMENTS - || group == 0 - || group > 1024 - || !group.is_multiple_of(32) - || p.head32 >= 32 - || u64::from(p.head_group) >= group - || !p.scales_offset.is_multiple_of(2) - || !p.planes_offset.is_multiple_of(4) - || !p.plane_stride_words.is_multiple_of(4) - || p.window_words > p.plane_stride_words - || u64::from(p.packet_bytes) < BOOK_REGION_BYTES - { - return false; - } - // Every staged word / group the loop can touch exists, and every region - // lies inside the packet. let words_needed = (u64::from(p.head32) + count).div_ceil(32); let groups_needed = (u64::from(p.head_group) + count - 1) / group + 1; words_needed <= u64::from(p.window_words) @@ -50,96 +60,126 @@ pub fn kernel_decode(p: &DecodeParams, packet: &[u8], out: &mut [f32]) -> u32 { if !decode_params_valid(p) || packet.len() < p.packet_bytes as usize || out.len() < p.count as usize { return STATUS_BAD_ARGUMENT; } - let level = p.level; for block in 0..decode_grid(p.count) { - // Shared-memory book as f32, loaded by the first 2^L threads, then - // __syncthreads(). Any non-finite table entry flags the launch. - let mut book = [0f32; 32]; - for thread in 0..BLOCK_THREADS { - if thread < (1 << level) { - let bits = le16(packet, 2 * thread as usize); - if nonfinite_f16(bits) { - status |= STATUS_NONFINITE_INPUT; - } - book[thread as usize] = f16_to_f32(bits); - } - } + let (book, book_status) = load_book(p, packet); + status |= book_status; // ---- barrier ---- - for thread in 0..BLOCK_THREADS { - let i = block * BLOCK_THREADS + thread; - if i >= p.count { - continue; - } - let position = p.head32 + i; - let word = position / 32; - let bit = position % 32; - let group_index = (p.head_group + i) / p.group; - let mut code = 0u32; - for plane in 0..level { - let at = - p.planes_offset as usize + (plane as usize * p.plane_stride_words as usize + word as usize) * 4; - code = (code << 1) | ((le32(packet, at) >> bit) & 1); - } - let scale_bits = le16(packet, p.scales_offset as usize + 2 * group_index as usize); - if nonfinite_f16(scale_bits) { - status |= STATUS_NONFINITE_INPUT; - out[i as usize] = f32::from_bits(NAN_BITS); - continue; - } - // Single binary32 multiply (device: __fmul_rn), as in kar_codec. - out[i as usize] = book[code as usize] * f16_to_f32(scale_bits); - } + status |= decode_block(p, packet, &book, block, out); } status } +/// Shared-memory book as f32, loaded by the first 2^L threads, then +/// __syncthreads(). Any non-finite table entry flags the launch. +fn load_book(p: &DecodeParams, packet: &[u8]) -> ([f32; 32], u32) { + let mut book = [0f32; 32]; + let mut status = 0u32; + for thread in 0..BLOCK_THREADS { + if thread < (1 << p.level) { + let bits = le16(packet, 2 * thread as usize); + if nonfinite_f16(bits) { + status |= STATUS_NONFINITE_INPUT; + } + book[thread as usize] = f16_to_f32(bits); + } + } + (book, status) +} + +/// One thread per output element of the block. +fn decode_block(p: &DecodeParams, packet: &[u8], book: &[f32; 32], block: u32, out: &mut [f32]) -> u32 { + let mut status = 0u32; + for thread in 0..BLOCK_THREADS { + let i = block * BLOCK_THREADS + thread; + if i >= p.count { + continue; + } + status |= decode_element(p, packet, book, i, out); + } + status +} + +fn decode_element(p: &DecodeParams, packet: &[u8], book: &[f32; 32], i: u32, out: &mut [f32]) -> u32 { + let position = p.head32 + i; + let word = position / 32; + let bit = position % 32; + let group_index = (p.head_group + i) / p.group; + let mut code = 0u32; + for plane in 0..p.level { + let at = p.planes_offset as usize + (plane as usize * p.plane_stride_words as usize + word as usize) * 4; + code = (code << 1) | ((le32(packet, at) >> bit) & 1); + } + let scale_bits = le16(packet, p.scales_offset as usize + 2 * group_index as usize); + if nonfinite_f16(scale_bits) { + out[i as usize] = f32::from_bits(NAN_BITS); + return STATUS_NONFINITE_INPUT; + } + // Single binary32 multiply (device: __fmul_rn), as in kar_codec. + out[i as usize] = book[code as usize] * f16_to_f32(scale_bits); + 0 +} + /// Literal model of `leleka_kar_multiply_f32`: one block per (row, token), /// 256 lanes striding the columns with separately rounded multiply/add, then /// the fixed 128..1 shared-memory tree. Output is `[token][row]`. -#[allow(clippy::needless_range_loop)] // lane indices mirror threadIdx.x pub fn kernel_multiply(weights: &[f32], input: &[f32], columns: u32, rows: u32, tokens: u32, out: &mut [f32]) -> u32 { let (cols, nrows) = (columns as usize, rows as usize); - if columns == 0 - || rows == 0 - || tokens == 0 - || tokens > MAX_TOKENS - || u64::from(columns) > MAX_COLUMNS - || u64::from(columns) * u64::from(rows) > MAX_RANGE_ELEMENTS - || weights.len() < cols * nrows - || input.len() < cols * tokens as usize - || out.len() < nrows * tokens as usize - { + if !multiply_args_ok(weights, input, (columns, rows, tokens), out.len()) { return STATUS_BAD_ARGUMENT; } let mut status = 0u32; for token in 0..tokens as usize { for row in 0..nrows { - let mut partial = [0f32; BLOCK_THREADS as usize]; - for lane in 0..BLOCK_THREADS as usize { - let mut sum = 0f32; - let mut column = lane; - while column < cols { - sum += weights[row * cols + column] * input[token * cols + column]; - column += BLOCK_THREADS as usize; - } - partial[lane] = sum; - } - let mut stride = (BLOCK_THREADS / 2) as usize; - while stride > 0 { - for lane in 0..stride { - partial[lane] += partial[lane + stride]; - } - stride >>= 1; - } - if !partial[0].is_finite() { + let total = row_total(&weights[row * cols..(row + 1) * cols], &input[token * cols..(token + 1) * cols]); + if !total.is_finite() { status |= STATUS_NONFINITE_OUTPUT; } - out[token * nrows + row] = partial[0]; + out[token * nrows + row] = total; } } status } +fn multiply_args_ok(weights: &[f32], input: &[f32], (columns, rows, tokens): (u32, u32, u32), out_len: usize) -> bool { + let (cols, nrows) = (columns as usize, rows as usize); + columns != 0 + && rows != 0 + && tokens != 0 + && tokens <= MAX_TOKENS + && u64::from(columns) <= MAX_COLUMNS + && u64::from(columns) * u64::from(rows) <= MAX_RANGE_ELEMENTS + && weights.len() >= cols * nrows + && input.len() >= cols * tokens as usize + && out_len >= nrows * tokens as usize +} + +/// One block: 256 lanes striding the columns, then the fixed 128..1 tree. +fn row_total(weights: &[f32], input: &[f32]) -> f32 { + let mut partial = [0f32; BLOCK_THREADS as usize]; + lane_sums(weights, input, &mut partial); + let mut stride = (BLOCK_THREADS / 2) as usize; + while stride > 0 { + for lane in 0..stride { + partial[lane] += partial[lane + stride]; + } + stride >>= 1; + } + partial[0] +} + +#[allow(clippy::needless_range_loop)] // lane indices mirror threadIdx.x +fn lane_sums(weights: &[f32], input: &[f32], partial: &mut [f32; BLOCK_THREADS as usize]) { + for lane in 0..BLOCK_THREADS as usize { + let mut sum = 0f32; + let mut column = lane; + while column < weights.len() { + sum += weights[column] * input[column]; + column += BLOCK_THREADS as usize; + } + partial[lane] = sum; + } +} + /// Model of `leleka_kar_swiglu_f32`: `silu(gate) * up` in binary32. The device /// uses `expf`, which is not guaranteed to match Rust's `exp` bit for bit; the /// GPU smoke compares this stage with a tolerance, never as a bit claim. diff --git a/crates/model-format/src/kar_kernel_model/impl_fmt_display_for.rs b/crates/model-format/src/kar_kernel_model/impl_fmt_display_for.rs index bdd330e4..3dfe69c8 100644 --- a/crates/model-format/src/kar_kernel_model/impl_fmt_display_for.rs +++ b/crates/model-format/src/kar_kernel_model/impl_fmt_display_for.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: impl fmt_Display_for, impl std_error_Error, fn reject, fn round_up, impl WindowPlan, fn plan_window .... +//! Moved out of the parent module by STRA-338: impl fmt_Display_for, impl std_error_Error, fn reject, fn round_up, impl +//! WindowPlan, fn plan_window .... #[allow(unused_imports)] use super::*; @@ -40,6 +41,36 @@ impl WindowPlan { /// Plan one bounded window of a NESTED record at `level`. pub fn plan_window(record: &KarNestedRecord, level: u8, start: u64, count: u64) -> Result { + check_window_request(record, level, count)?; + let end = start.checked_add(count).filter(|end| *end <= record.n_elements); + let Some(end) = end else { + return reject("KAR decode range exceeds the tensor"); + }; + let g = window_geometry(record, level, start, end)?; + Ok(WindowPlan { + level, + group: record.group, + start, + count: to_u32(count), + first_word: g.first_word, + first_group: g.first_group, + book: ByteRange { archive_offset: record.books_offset + g.book_skip, len: g.book_len, packet_offset: 0 }, + scales: ByteRange { + archive_offset: record.scales_offset + g.first_group * 2, + len: g.scales_len, + packet_offset: BOOK_REGION_BYTES, + }, + planes: g.plane_ranges(record, level), + params: g.params(record, level, count), + }) +} + +/// All values converted here were bounded by `plan_window` (count <= 2^24, packet < 2^31). +fn to_u32(v: u64) -> u32 { + v as u32 +} + +fn check_window_request(record: &KarNestedRecord, level: u8, count: u64) -> Result<()> { if record.validate().is_err() { return reject("KAR nested record layout is invalid"); } @@ -58,78 +89,119 @@ pub fn plan_window(record: &KarNestedRecord, level: u8, start: u64, count: u64) if count == 0 || count > MAX_RANGE_ELEMENTS { return reject("KAR decode count must be 1..=16,777,216"); } - let end = start.checked_add(count).filter(|end| *end <= record.n_elements); - let Some(end) = end else { - return reject("KAR decode range exceeds the tensor"); - }; + Ok(()) +} + +/// The word, group and packet geometry of a window `[start, end)` of a record. +struct WindowGeometry { + first_word: u64, + window_words: u64, + first_group: u64, + window_groups: u64, + head32: u64, + head_group: u64, + book_skip: u64, + book_len: u64, + scales_len: u64, + stride: u64, + planes_packet: u64, + plane_stride_words: u64, + packet_bytes: u64, +} + +fn window_geometry(record: &KarNestedRecord, level: u8, start: u64, end: u64) -> Result { let group = u64::from(record.group); let first_word = start / 32; let window_words = end.div_ceil(32) - first_word; let first_group = start / group; let window_groups = end.div_ceil(group) - first_group; - let head32 = start % 32; - let head_group = start % group; - let level_u64 = u64::from(level); + let (book_skip, book_len) = check_book(record, level)?; + let scales_len = check_scales(record, first_group, window_groups)?; + let stride = check_plane_words(record, first_word, window_words)?; + let (planes_packet, plane_stride_words, packet_bytes) = packet_layout(level, window_words, scales_len)?; + Ok(WindowGeometry { + first_word, + window_words, + first_group, + window_groups, + head32: start % 32, + head_group: start % group, + book_skip, + book_len, + scales_len, + stride, + planes_packet, + plane_stride_words, + packet_bytes, + }) +} + +/// (skip, length) of the book of `level` inside the record's books. +fn check_book(record: &KarNestedRecord, level: u8) -> Result<(u64, u64)> { // Book for level L sits after the tables for levels 1..L-1: (2^L - 2) f16. let book_skip = ((1u64 << level) - 2) * 2; let book_len = (1u64 << level) * 2; if book_skip + book_len > record.books_bytes { return reject("KAR book range exceeds the record"); } - let scales_len = window_groups * 2; + Ok((book_skip, book_len)) +} + +/// Bytes of the scales of the window. +fn check_scales(record: &KarNestedRecord, first_group: u64, window_groups: u64) -> Result { if (first_group + window_groups) * 2 > record.scales_bytes { return reject("KAR scale range exceeds the record"); } + Ok(window_groups * 2) +} + +/// The plane stride of the record, after the window's words are known to fit it. +fn check_plane_words(record: &KarNestedRecord, first_word: u64, window_words: u64) -> Result { let stride = u64::from(record.plane_stride_bytes); - let words_len = window_words * 4; if (first_word + window_words) * 4 > stride { return reject("KAR plane word range exceeds the plane stride"); } - let scales_packet = BOOK_REGION_BYTES; - let planes_packet = round_up(scales_packet + scales_len, PACKET_ALIGN); + Ok(stride) +} + +/// (plane offset in the packet, plane stride in words, packet bytes) of a window. +fn packet_layout(level: u8, window_words: u64, scales_len: u64) -> Result<(u64, u64, u64)> { + let planes_packet = round_up(BOOK_REGION_BYTES + scales_len, PACKET_ALIGN); let plane_stride_words = round_up(window_words, 4); - let packet_bytes = planes_packet + level_u64 * plane_stride_words * 4; + let packet_bytes = planes_packet + u64::from(level) * plane_stride_words * 4; if packet_bytes > u64::from(u32::MAX >> 1) { return reject("KAR packet exceeds 2 GiB"); } - let planes = (0..level_u64) - .map(|plane| ByteRange { - archive_offset: record.planes_offset + plane * stride + first_word * 4, - len: words_len, - packet_offset: planes_packet + plane * plane_stride_words * 4, - }) - .collect(); - // All values below were bounded above (count <= 2^24, packet < 2^31). - let to_u32 = |v: u64| v as u32; - Ok(WindowPlan { - level, - group: record.group, - start, - count: to_u32(count), - first_word, - first_group, - book: ByteRange { archive_offset: record.books_offset + book_skip, len: book_len, packet_offset: 0 }, - scales: ByteRange { - archive_offset: record.scales_offset + first_group * 2, - len: scales_len, - packet_offset: scales_packet, - }, - planes, - params: DecodeParams { + Ok((planes_packet, plane_stride_words, packet_bytes)) +} + +impl WindowGeometry { + fn plane_ranges(&self, record: &KarNestedRecord, level: u8) -> Vec { + (0..u64::from(level)) + .map(|plane| ByteRange { + archive_offset: record.planes_offset + plane * self.stride + self.first_word * 4, + len: self.window_words * 4, + packet_offset: self.planes_packet + plane * self.plane_stride_words * 4, + }) + .collect() + } + + fn params(&self, record: &KarNestedRecord, level: u8, count: u64) -> DecodeParams { + DecodeParams { level: u32::from(level), staged_planes: u32::from(level), count: to_u32(count), - head32: to_u32(head32), - head_group: to_u32(head_group), + head32: to_u32(self.head32), + head_group: to_u32(self.head_group), group: record.group, - scales_offset: to_u32(scales_packet), - planes_offset: to_u32(planes_packet), - plane_stride_words: to_u32(plane_stride_words), - window_words: to_u32(window_words), - window_groups: to_u32(window_groups), - packet_bytes: to_u32(packet_bytes), - }, - }) + scales_offset: to_u32(BOOK_REGION_BYTES), + planes_offset: to_u32(self.planes_packet), + plane_stride_words: to_u32(self.plane_stride_words), + window_words: to_u32(self.window_words), + window_groups: to_u32(self.window_groups), + packet_bytes: to_u32(self.packet_bytes), + } + } } /// Plan `rows` complete rows starting at `first_row`. A row is `dims[0]` diff --git a/crates/model-format/src/kar_levels/impl_fmt_display_for.rs b/crates/model-format/src/kar_levels/impl_fmt_display_for.rs index 057d0e1d..2d36a0c1 100644 --- a/crates/model-format/src/kar_levels/impl_fmt_display_for.rs +++ b/crates/model-format/src/kar_levels/impl_fmt_display_for.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: impl fmt_Display_for, impl std_error_Error, impl TensorClass, impl ClassLevels, fn check_level, impl ArchiveView .... +//! Moved out of the parent module by STRA-338: impl fmt_Display_for, impl std_error_Error, impl TensorClass, impl +//! ClassLevels, fn check_level, impl ArchiveView .... #[allow(unused_imports)] use super::*; diff --git a/crates/model-format/src/kar_levels/impl_selection.rs b/crates/model-format/src/kar_levels/impl_selection.rs index c2af56b8..b6868d9b 100644 --- a/crates/model-format/src/kar_levels/impl_selection.rs +++ b/crates/model-format/src/kar_levels/impl_selection.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: impl Selection, fn align, impl GpuWindow, impl RowShape, impl GpuRows, impl ScratchBytes .... +//! Moved out of the parent module by STRA-338: impl Selection, fn align, impl GpuWindow, impl RowShape, impl GpuRows, +//! impl ScratchBytes .... #[allow(unused_imports)] use super::*; diff --git a/crates/model-format/src/kar_nested.rs b/crates/model-format/src/kar_nested.rs index 9b655df3..f22b3aa0 100644 --- a/crates/model-format/src/kar_nested.rs +++ b/crates/model-format/src/kar_nested.rs @@ -79,38 +79,51 @@ impl KarNestedRecord { /// Re-derive the inspector's nested-section rules. Byte-for-byte the same /// formulas as `inspect_file`, so hand-built descriptors cannot be looser. pub fn validate(&self) -> Result<(), KarError> { - let fail = |message: &'static str| Err(KarError::Format(message)); let group = u64::from(self.group); - let planes = u64::from(self.planes_stored); - if group == 0 - || group > 1024 - || !group.is_multiple_of(32) - || !(1..=16).contains(&self.planes_stored) - || self.planes_min == 0 - || self.planes_min > self.planes_max - || self.planes_max > self.planes_stored - || self.nesting > 1 - { - return fail("invalid KAR nested tensor parameters"); + if !self.parameters_valid(group) { + return Err(KarError::Format("invalid KAR nested tensor parameters")); } - if self.dimensions.is_empty() - || self.dimensions.len() > 4 - || self.n_elements == 0 - || self.dimensions.iter().try_fold(1u64, |acc, dim| acc.checked_mul(*dim)) != Some(self.n_elements) - { - return fail("KAR tensor element count mismatch"); + if !self.shape_valid() { + return Err(KarError::Format("KAR tensor element count mismatch")); } let rounded = self.n_elements.div_ceil(group).checked_mul(group).ok_or(KarError::Format("KAR padded count overflow"))?; if self.n_padded != rounded { - return fail("KAR padded tensor count mismatch"); + return Err(KarError::Format("KAR padded tensor count mismatch")); } - let expected_scales = + let expected = self.expected_layout(group)?; + if !self.layout_matches(&expected) { + return Err(KarError::Format("invalid KAR nested tensor section layout")); + } + Ok(()) + } + + fn parameters_valid(&self, group: u64) -> bool { + group != 0 + && group <= 1024 + && group.is_multiple_of(32) + && (1..=16).contains(&self.planes_stored) + && self.planes_min != 0 + && self.planes_min <= self.planes_max + && self.planes_max <= self.planes_stored + && self.nesting <= 1 + } + + fn shape_valid(&self) -> bool { + !self.dimensions.is_empty() + && self.dimensions.len() <= 4 + && self.n_elements != 0 + && self.dimensions.iter().try_fold(1u64, |acc, dim| acc.checked_mul(*dim)) == Some(self.n_elements) + } + + /// Where the pieces of the section must lie, from the sizes this record states. + fn expected_layout(&self, group: u64) -> Result { + let scales_bytes = (self.n_padded / group).checked_mul(2).ok_or(KarError::Format("KAR scale count overflow"))?; - let expected_books = (1u64 << (planes + 2)) - 4; + let books_bytes = (1u64 << (u64::from(self.planes_stored) + 2)) - 4; let plane_words_bytes = (self.n_padded / 32).checked_mul(4).ok_or(KarError::Format("KAR plane size overflow"))?; - let expected_stride = round_up(plane_words_bytes, 16).ok_or(KarError::Format("KAR plane stride overflow"))?; + let stride = round_up(plane_words_bytes, 16).ok_or(KarError::Format("KAR plane stride overflow"))?; let books_start = self .scales_offset .checked_add(self.scales_bytes) @@ -125,18 +138,29 @@ impl KarNestedRecord { .section_offset .checked_add(self.section_bytes) .ok_or(KarError::Format("KAR tensor section overflow"))?; - if self.scales_offset != self.section_offset - || self.scales_bytes != expected_scales - || self.books_offset != books_start - || self.books_bytes != expected_books - || self.planes_offset != planes_start - || u64::from(self.plane_stride_bytes) != expected_stride - || self.planes_offset.checked_add(planes * expected_stride).is_none_or(|end| end > section_end) - { - return fail("invalid KAR nested tensor section layout"); - } - Ok(()) + Ok(ExpectedLayout { scales_bytes, books_bytes, stride, books_start, planes_start, section_end }) } + + fn layout_matches(&self, expected: &ExpectedLayout) -> bool { + let planes = u64::from(self.planes_stored); + self.scales_offset == self.section_offset + && self.scales_bytes == expected.scales_bytes + && self.books_offset == expected.books_start + && self.books_bytes == expected.books_bytes + && self.planes_offset == expected.planes_start + && u64::from(self.plane_stride_bytes) == expected.stride + && self.planes_offset.checked_add(planes * expected.stride).is_some_and(|end| end <= expected.section_end) + } +} + +/// The sizes and offsets `KarNestedRecord::validate` derives from a record's own fields. +struct ExpectedLayout { + scales_bytes: u64, + books_bytes: u64, + stride: u64, + books_start: u64, + planes_start: u64, + section_end: u64, } impl KarInspection { diff --git a/crates/model-format/src/native_dense_plan.rs b/crates/model-format/src/native_dense_plan.rs index 7479ff84..a12317e6 100644 --- a/crates/model-format/src/native_dense_plan.rs +++ b/crates/model-format/src/native_dense_plan.rs @@ -1,6 +1,7 @@ //! Literal host port of the Original `src/core/native_dense.cpp` (`NativeDense::served_names`, //! `keep_unquantized_ple_key`, and the whole planning/validation half of `NativeDense::load`): which GGUF tensors are -//! served natively, split-shard consistency, payload span validation, bytes per matrix and the shared Q8_1 scratch size. +//! served natively, split-shard consistency, payload span validation, bytes per matrix and the shared Q8_1 scratch +//! size. //! The device upload (`cudaMalloc` + `cudaMemcpy` + attaching `native_data`/`native_type`/`native_q8_1`) is the //! runtime's; this module produces the exact list it must perform and refuses with the Original's messages. //! @@ -15,26 +16,27 @@ pub fn native_mmvq_supported(ggml_type: u32) -> bool { } /// The `(block_elems, block_bytes)` table of `native_mmvq_weight_bytes` (the i-quant rows come from `iq_row_bytes` at /// 256 elements: IQ2_XXS 66, IQ2_XS 74, IQ3_XXS 98, IQ3_S 110, IQ2_S 82, IQ4_XS-family type 29 = 56 bytes). +const WEIGHT_BLOCKS: &[(u32, u64, u64)] = &[ + (2, 32, 18), + (20, 32, 18), + (6, 32, 22), + (7, 32, 24), + (8, 32, 34), + (11, 256, 110), + (12, 256, 144), + (13, 256, 176), + (14, 256, 210), + (23, 256, 136), + (42, 64, 18), + (16, 256, 66), + (17, 256, 74), + (18, 256, 98), + (21, 256, 110), + (22, 256, 82), + (29, 256, 56), +]; fn weight_block(ggml_type: u32) -> Option<(u64, u64)> { - Some(match ggml_type { - 2 | 20 => (32, 18), - 6 => (32, 22), - 7 => (32, 24), - 8 => (32, 34), - 11 => (256, 110), - 12 => (256, 144), - 13 => (256, 176), - 14 => (256, 210), - 23 => (256, 136), - 42 => (64, 18), - 16 => (256, 66), - 17 => (256, 74), - 18 => (256, 98), - 21 => (256, 110), - 22 => (256, 82), - 29 => (256, 56), - _ => return None, - }) + WEIGHT_BLOCKS.iter().find(|entry| entry.0 == ggml_type).map(|entry| (entry.1, entry.2)) } /// `native_mmvq_weight_bytes`; the error texts are the exceptions the Original throws. pub fn native_mmvq_weight_bytes(ggml_type: u32, n_in: i64, n_out: i64) -> Result { @@ -91,7 +93,8 @@ pub fn eligible(row: &TensorRow, include_ple_key: bool) -> bool { if !name.starts_with("blk.") { return false; } - // Match the native PLE kernel: Q2_0, IQ3_XXS, IQ4_XS and Q8_0 (UD-Q4_K_XL). Other keys retain the packed BF16 fallback. + // Match the native PLE kernel: Q2_0, IQ3_XXS, IQ4_XS and Q8_0 (UD-Q4_K_XL). Other keys retain the packed BF16 + // fallback. if name == "blk.1.ple_key.weight" { return include_ple_key && matches!(row.kind, 42 | 18 | 23 | 8); } @@ -168,6 +171,147 @@ fn fail(message: impl Into) -> Result { Err(message.into()) } +/// The state of `plan_load` while it walks the shards. +#[derive(Default)] +struct Planner { + items: Vec, + seen: BTreeSet, + max_in: i64, + total: u64, + split_count: u64, + split_tensors: u64, + split_numbers: BTreeSet, + have_architecture: bool, +} + +const KEY: &str = "blk.1.ple_key.weight"; + +impl Planner { + /// Architecture and split metadata of the shard: the first shard defines them, the others must match. + fn check_split(&mut self, shard: &ShardInfo) -> Result<(), String> { + if shard.has_architecture { + self.first_shard(shard)?; + } else if !self.additional_shard_matches(shard) { + return fail( + "native dense: additional shard must match the architecture-validated first shard's split metadata", + ); + } + if let Some(n) = shard.split_no + && !self.split_numbers.insert(n) + { + return fail("native dense: duplicate split shard number"); + } + Ok(()) + } + + fn first_shard(&mut self, shard: &ShardInfo) -> Result<(), String> { + if !shard.architecture_error.is_empty() { + return Err(shard.architecture_error.clone()); + } + self.have_architecture = true; + if let (Some(c), Some(0), Some(t)) = (shard.split_count, shard.split_no, shard.split_tensors) + && c > 1 + { + self.split_count = c; + self.split_tensors = t; + } + Ok(()) + } + + fn additional_shard_matches(&self, shard: &ShardInfo) -> bool { + self.have_architecture + && self.split_count != 0 + && shard.split_count == Some(self.split_count) + && shard.split_no.is_some_and(|n| n != 0 && n < self.split_count) + && shard.split_tensors == Some(self.split_tensors) + } + + /// The served matrices of one shard, appended to the plan. + fn collect_items Option + ?Sized>( + &mut self, + shard_index: usize, + shard: &ShardInfo, + canonical: &F, + include_ple_key: bool, + ) -> Result<(), String> { + for tensor in &shard.tensors { + if eligible(tensor, include_ple_key) { + self.add_tensor(shard_index, shard, tensor, canonical)?; + } + } + Ok(()) + } + + fn add_tensor Option + ?Sized>( + &mut self, + shard_index: usize, + shard: &ShardInfo, + tensor: &TensorRow, + canonical: &F, + ) -> Result<(), String> { + if !self.seen.insert(tensor.name.clone()) { + return fail(format!("native dense: duplicate tensor {}", tensor.name)); + } + let Some(reference) = canonical(&tensor.name) else { + return fail(format!("native dense: tensor absent from canonical table: {}", tensor.name)); + }; + if reference.native_attached { + return fail("native dense: override already attached"); + } + // #326: the pack keeps an unquantized (--compat-bf16) key, which the PLE reads from the arena + if !native_mmvq_supported(tensor.kind) || (tensor.name == KEY && !reference.quantized) { + return Ok(()); + } + if !matrix_compatible(tensor, &reference) { + return fail(format!("native dense: incompatible matrix {}", tensor.name)); + } + self.push_matrix(shard_index, shard, tensor, &reference) + } + + /// Adds the compatible matrix to the plan, with its native byte count. + fn push_matrix( + &mut self, + shard_index: usize, + shard: &ShardInfo, + tensor: &TensorRow, + reference: &Canonical, + ) -> Result<(), String> { + let bytes = native_mmvq_weight_bytes(tensor.kind, reference.ne0, reference.ne1) + .map_err(|e| format!("native dense: {e}"))?; + self.max_in = self.max_in.max(reference.ne0); + self.total += bytes; + self.items.push(DenseItem { + name: tensor.name.clone(), + ggml_type: tensor.kind, + bytes, + ne0: reference.ne0, + ne1: reference.ne1, + shard: shard_index, + file_offset: shard.data_start + tensor.offset, + }); + Ok(()) + } + + fn finish(self) -> Result { + if self.items.is_empty() { + return fail("native dense: no supported GDN/QSA matrices in supplied shards"); + } + let scratch_bytes = native_q8_1_bytes(self.max_in).map_err(|e| format!("native dense scratch: {e}"))?; + Ok(DensePlan { items: self.items, max_in: self.max_in, total_bytes: self.total, scratch_bytes }) + } +} + +/// The directory tensor is a two-dimensional quantized matrix of the canonical shape, within int32 dimensions. +fn matrix_compatible(tensor: &TensorRow, reference: &Canonical) -> bool { + let int32 = 1..=i64::from(i32::MAX); + reference.quantized + && tensor.shape.len() == 2 + && int32.contains(&reference.ne0) + && int32.contains(&reference.ne1) + && tensor.shape[0] == reference.ne0 as u64 + && tensor.shape[1] == reference.ne1 as u64 +} + /// Everything `NativeDense::load` does before its first `cudaMalloc`, in the Original's order and with its messages. pub fn plan_load( shards: &[ShardInfo], @@ -177,133 +321,58 @@ pub fn plan_load( if shards.is_empty() { return fail("native dense: at least one GGUF shard is required"); } - let mut items: Vec = Vec::new(); - let mut seen = BTreeSet::new(); - let mut max_in = 0i64; - let mut total = 0u64; - let (mut split_count, mut split_tensors) = (0u64, 0u64); - let mut split_numbers = BTreeSet::new(); - let mut have_architecture = false; + let mut planner = Planner::default(); for (shard_index, shard) in shards.iter().enumerate() { - let (count, number, tensors) = (shard.split_count, shard.split_no, shard.split_tensors); - if shard.has_architecture { - if !shard.architecture_error.is_empty() { - return Err(shard.architecture_error.clone()); - } - have_architecture = true; - if let (Some(c), Some(0), Some(t)) = (count, number, tensors) - && c > 1 - { - split_count = c; - split_tensors = t; - } - } else if !have_architecture - || split_count == 0 - || count.is_none() - || number.is_none() - || tensors.is_none() - || count != Some(split_count) - || number == Some(0) - || number.is_some_and(|n| n >= split_count) - || tensors != Some(split_tensors) - { - return fail( - "native dense: additional shard must match the architecture-validated first shard's split metadata", - ); + planner.check_split(shard)?; + check_payload_spans(shard)?; + planner.collect_items(shard_index, shard, canonical, include_ple_key)?; + } + planner.finish() +} + +/// The payload offsets of a shard are distinct, and every directory span, including tensors we do not upload, lies +/// in the payload and overlaps no other: an ignored tensor must not overlap the native matrix that follows it. +fn check_payload_spans(shard: &ShardInfo) -> Result<(), String> { + let mut offsets: Vec = shard.tensors.iter().map(|t| t.offset).collect(); + offsets.sort_unstable(); + if offsets.windows(2).any(|w| w[0] == w[1]) { + return fail("native dense: tensor payload offsets overlap"); + } + let payload = shard.file_size.saturating_sub(shard.data_start); + for tensor in &shard.tensors { + let bytes = tensor_payload_bytes(tensor)?; + if tensor.offset > payload || bytes > payload - tensor.offset { + return fail(format!("native dense: truncated payload {}", tensor.name)); } - if let Some(n) = number - && !split_numbers.insert(n) - { - return fail("native dense: duplicate split shard number"); - } - let mut offsets: Vec = shard.tensors.iter().map(|t| t.offset).collect(); - offsets.sort_unstable(); - if offsets.windows(2).any(|w| w[0] == w[1]) { - return fail("native dense: tensor payload offsets overlap"); - } - // Validate every directory span, including tensors we do not upload: an ignored tensor must not overlap the - // native matrix that follows it. - let payload = shard.file_size.saturating_sub(shard.data_start); - for tensor in &shard.tensors { - let geometry = block_geometry(tensor.kind); - let ok_geometry = - geometry.is_some_and(|(elems, _)| !tensor.shape.is_empty() && tensor.shape[0] % elems == 0); - let (block_elements, block_bytes) = match geometry { - Some(g) if ok_geometry => g, - _ => return fail(format!("native dense: invalid block geometry {}", tensor.name)), - }; - let mut elements = 1u64; - for &dimension in &tensor.shape { - if dimension == 0 || elements > u64::MAX / dimension { - return fail(format!("native dense: invalid tensor extent {}", tensor.name)); - } - elements *= dimension; - } - let blocks = elements / block_elements; - if blocks > u64::MAX / block_bytes { - return fail(format!("native dense: tensor byte count overflow {}", tensor.name)); - } - let bytes = blocks * block_bytes; - if tensor.offset > payload || bytes > payload - tensor.offset { - return fail(format!("native dense: truncated payload {}", tensor.name)); - } - // std::upper_bound: the first offset strictly greater than this tensor's - let next = offsets.partition_point(|o| *o <= tensor.offset); - if next != offsets.len() && bytes > offsets[next] - tensor.offset { - return fail(format!("native dense: overlapping payload {}", tensor.name)); - } - } - for tensor in &shard.tensors { - if !eligible(tensor, include_ple_key) { - continue; - } - if !seen.insert(tensor.name.clone()) { - return fail(format!("native dense: duplicate tensor {}", tensor.name)); - } - let Some(reference) = canonical(&tensor.name) else { - return fail(format!("native dense: tensor absent from canonical table: {}", tensor.name)); - }; - if reference.native_attached { - return fail("native dense: override already attached"); - } - if !native_mmvq_supported(tensor.kind) { - continue; - } - // #326: the pack keeps an unquantized (--compat-bf16) key, which the PLE reads from the arena - if tensor.name == "blk.1.ple_key.weight" && !reference.quantized { - continue; - } - if !reference.quantized - || tensor.shape.len() != 2 - || reference.ne0 <= 0 - || reference.ne0 > i64::from(i32::MAX) - || reference.ne1 <= 0 - || reference.ne1 > i64::from(i32::MAX) - || tensor.shape[0] != reference.ne0 as u64 - || tensor.shape[1] != reference.ne1 as u64 - { - return fail(format!("native dense: incompatible matrix {}", tensor.name)); - } - let bytes = native_mmvq_weight_bytes(tensor.kind, reference.ne0, reference.ne1) - .map_err(|e| format!("native dense: {e}"))?; - max_in = max_in.max(reference.ne0); - total += bytes; - items.push(DenseItem { - name: tensor.name.clone(), - ggml_type: tensor.kind, - bytes, - ne0: reference.ne0, - ne1: reference.ne1, - shard: shard_index, - file_offset: shard.data_start + tensor.offset, - }); + // std::upper_bound: the first offset strictly greater than this tensor's + let next = offsets.partition_point(|o| *o <= tensor.offset); + if next != offsets.len() && bytes > offsets[next] - tensor.offset { + return fail(format!("native dense: overlapping payload {}", tensor.name)); } } - if items.is_empty() { - return fail("native dense: no supported GDN/QSA matrices in supplied shards"); + Ok(()) +} + +/// The bytes of a directory tensor by its block geometry, refusing a bad geometry, extent or byte count. +fn tensor_payload_bytes(tensor: &TensorRow) -> Result { + let geometry = block_geometry(tensor.kind); + let ok_geometry = geometry.is_some_and(|(elems, _)| !tensor.shape.is_empty() && tensor.shape[0] % elems == 0); + let (block_elements, block_bytes) = match geometry { + Some(g) if ok_geometry => g, + _ => return fail(format!("native dense: invalid block geometry {}", tensor.name)), + }; + let mut elements = 1u64; + for &dimension in &tensor.shape { + if dimension == 0 || elements > u64::MAX / dimension { + return fail(format!("native dense: invalid tensor extent {}", tensor.name)); + } + elements *= dimension; } - let scratch_bytes = native_q8_1_bytes(max_in).map_err(|e| format!("native dense scratch: {e}"))?; - Ok(DensePlan { items, max_in, total_bytes: total, scratch_bytes }) + let blocks = elements / block_elements; + if blocks > u64::MAX / block_bytes { + return fail(format!("native dense: tensor byte count overflow {}", tensor.name)); + } + Ok(blocks * block_bytes) } /// Name -> attached type, as the runtime reports it after publishing (`ref.native_type`). diff --git a/crates/model-format/src/pinned_arena_plan/fnv1a64_fn.rs b/crates/model-format/src/pinned_arena_plan/fnv1a64_fn.rs index aeb88ca5..1cd2a572 100644 --- a/crates/model-format/src/pinned_arena_plan/fnv1a64_fn.rs +++ b/crates/model-format/src/pinned_arena_plan/fnv1a64_fn.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: fn fnv1a64, impl SharedArenaHeader, fn plan_shared_file, fn shared_mapping_note, fn open_shared_arena_file, fn arena_pin_cap_gib .... +//! Moved out of the parent module by STRA-338: fn fnv1a64, impl SharedArenaHeader, fn plan_shared_file, fn +//! shared_mapping_note, fn open_shared_arena_file, fn arena_pin_cap_gib .... #[allow(unused_imports)] use super::*; @@ -16,6 +17,13 @@ impl SharedArenaHeader { pack_hash, } } + /// The header of a version-1 arena of `bytes` bytes (the pack hash is compared separately). + fn describes(&self, bytes: u64) -> bool { + self.magic == SHARED_ARENA_MAGIC + && self.version == 1 + && u64::from(self.header_bytes) == SHARED_ARENA_HEADER_BYTES + && self.arena_bytes == bytes + } pub fn encode(&self) -> [u8; SHARED_ARENA_HEADER_STRUCT_BYTES] { let mut out = [0u8; SHARED_ARENA_HEADER_STRUCT_BYTES]; out[0..16].copy_from_slice(&self.magic); @@ -50,22 +58,24 @@ pub fn plan_shared_file( return Err("shared arena requires a nonzero pack hash".into()); } let file_bytes = SHARED_ARENA_HEADER_BYTES.checked_add(bytes).ok_or("shared arena size overflows its header")?; - let fresh = existing.is_none_or(|(size, _)| size == 0); - if fresh { - return Ok(SharedFileAction::Create { file_bytes, header: SharedArenaHeader::new(bytes, pack_hash) }); + match existing { + Some((size, head)) if size != 0 => check_existing_shared_file(path, (bytes, pack_hash, file_bytes), size, head), + _ => Ok(SharedFileAction::Create { file_bytes, header: SharedArenaHeader::new(bytes, pack_hash) }), } - let (size, head) = existing.expect("non-fresh has a state"); +} + +/// A shared arena file that already has content is reused only when its size and header are exactly the expected ones. +fn check_existing_shared_file( + path: &str, + (bytes, pack_hash, file_bytes): (u64, u64, u64), + size: u64, + head: &[u8], +) -> Result { if size != file_bytes { return Err(format!("shared arena {path} is {size} B, expected {file_bytes} B including its header")); } - let header = SharedArenaHeader::decode(head); - match header { - Some(h) - if h.magic == SHARED_ARENA_MAGIC - && h.version == 1 - && u64::from(h.header_bytes) == SHARED_ARENA_HEADER_BYTES - && h.arena_bytes == bytes => - { + match SharedArenaHeader::decode(head) { + Some(h) if h.describes(bytes) => { if h.pack_hash != pack_hash { return Err(format!( "shared arena {path} was written for pack hash {:016x}, expected {:016x}", @@ -90,25 +100,13 @@ pub fn open_shared_arena_file( bytes: u64, pack_hash: u64, ) -> Result<(std::fs::File, SharedFileAction), String> { - use std::os::unix::fs::{FileExt, OpenOptionsExt}; + use std::os::unix::fs::FileExt; let shown = path.display().to_string(); - if pack_hash == 0 { - return Err("shared arena requires a nonzero pack hash".into()); - } - if bytes > u64::MAX - SHARED_ARENA_HEADER_BYTES { - return Err("shared arena size overflows its header".into()); - } - let file = std::fs::OpenOptions::new() - .read(true) - .write(true) - .create(true) - .truncate(false) - .mode(0o600) - .open(path) - .map_err(|e| format!("cannot open shared arena {shown}: {e}"))?; + check_arena_request(bytes, pack_hash)?; + let file = open_arena_file(path, &shown)?; let size = file.metadata().map_err(|e| format!("cannot stat shared arena {shown}: {e}"))?.len(); let mut head = [0u8; SHARED_ARENA_HEADER_STRUCT_BYTES]; - let have_head = if size == 0 { false } else { file.read_exact_at(&mut head, 0).is_ok() }; + let have_head = size != 0 && file.read_exact_at(&mut head, 0).is_ok(); let plan = plan_shared_file(&shown, bytes, pack_hash, Some((size, if have_head { &head[..] } else { &[] })))?; if let SharedFileAction::Create { file_bytes, header } = &plan { file.set_len(*file_bytes).map_err(|e| format!("cannot size shared arena {shown}: {e}"))?; @@ -117,6 +115,30 @@ pub fn open_shared_arena_file( Ok((file, plan)) } +/// The pack hash is nonzero and the arena plus its header fits in 64 bits. +#[cfg(unix)] +fn check_arena_request(bytes: u64, pack_hash: u64) -> Result<(), String> { + if pack_hash == 0 { + return Err("shared arena requires a nonzero pack hash".into()); + } + if bytes > u64::MAX - SHARED_ARENA_HEADER_BYTES { + return Err("shared arena size overflows its header".into()); + } + Ok(()) +} + +#[cfg(unix)] +fn open_arena_file(path: &std::path::Path, shown: &str) -> Result { + use std::os::unix::fs::OpenOptionsExt; + std::fs::OpenOptions::new() + .read(true) + .write(true) + .create(true) + .truncate(false) + .mode(0o600) + .open(path) + .map_err(|e| format!("cannot open shared arena {shown}: {e}")) +} // -------------------------------------------------------------------------------- registration plan /// `STRATA_ARENA_PIN_GIB`: -1 unset/invalid (the engine decides), 0 no cap, N > 0 GiB, -2 "auto". diff --git a/crates/model-format/src/pinned_arena_plan/load_experts_fn.rs b/crates/model-format/src/pinned_arena_plan/load_experts_fn.rs index 8e4c058a..9dc0a6e3 100644 --- a/crates/model-format/src/pinned_arena_plan/load_experts_fn.rs +++ b/crates/model-format/src/pinned_arena_plan/load_experts_fn.rs @@ -18,7 +18,8 @@ pub fn load_experts( let off: Vec = (0..layers).map(|l| l * blobs_per_layer * blob_bytes).collect(); load_experts_ranges(path, dst, &off, &vec![n; layers as usize], threads, chunk) } -/// `load_experts_ranges`: reads layer `L` (`layer_bytes[L]` bytes at file offset `layer_off[L]`) into `dst[layer_off[L]..]` +/// `load_experts_ranges`: reads layer `L` (`layer_bytes[L]` bytes at file offset `layer_off[L]`) into +/// `dst[layer_off[L]..]` /// with `threads` workers, `chunk` bytes per read, and returns one FNV-1a per layer. A short read is an error, never a /// zero fill. #[cfg(unix)] @@ -30,24 +31,42 @@ pub fn load_experts_ranges( threads: usize, chunk: u64, ) -> LoadStats { - use std::sync::Mutex; - use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; - use std::time::Instant; let mut st = LoadStats { ok: true, layers: layer_off.len() as u64, bytes: layer_bytes.iter().sum(), ..Default::default() }; - let threads = threads.max(1); - let t0 = Instant::now(); - let fail = |mut st: LoadStats, message: String| { - eprintln!("load_experts: {message}"); - st.seconds = -1.0; - st.ok = false; - st.error = message; - st - }; + let t0 = std::time::Instant::now(); if layer_off.len() != layer_bytes.len() || chunk == 0 { - return fail(st, "layer offset and size lists differ, or the chunk is empty".into()); + return load_failure(st, "layer offset and size lists differ, or the chunk is empty".into()); } - // carve disjoint destination windows (hardening: the Original trusts the ranges) + let windows = match carve_windows(dst, layer_off, layer_bytes) { + Ok(windows) => windows, + Err(message) => return load_failure(st, message), + }; + match run_workers(path, windows, threads.max(1), chunk) { + Ok(done) => { + done.fill(&mut st); + st.seconds = t0.elapsed().as_secs_f64(); + st + } + Err(message) => load_failure(st, message), + } +} + +#[cfg(unix)] +fn load_failure(mut st: LoadStats, message: String) -> LoadStats { + eprintln!("load_experts: {message}"); + st.seconds = -1.0; + st.ok = false; + st.error = message; + st +} + +/// The destination window of every layer: (file offset, disjoint slice of `dst`). +#[cfg(unix)] +type LayerWindows<'a> = Vec>>; + +/// Carves disjoint destination windows (hardening: the Original trusts the ranges). +#[cfg(unix)] +fn carve_windows<'a>(dst: &'a mut [u8], layer_off: &[u64], layer_bytes: &[u64]) -> Result, String> { let mut order: Vec = (0..layer_off.len()).collect(); order.sort_by_key(|&l| layer_off[l]); let mut windows: Vec> = (0..layer_off.len()).map(|_| None).collect(); @@ -56,7 +75,7 @@ pub fn load_experts_ranges( for &l in &order { let (o, n) = (layer_off[l], layer_bytes[l]); if o < cursor || o.checked_add(n).is_none_or(|e| e > cursor + rest.len() as u64) { - return fail(st, format!("layer {l}: range {o}+{n} overlaps another layer or leaves the destination")); + return Err(format!("layer {l}: range {o}+{n} overlaps another layer or leaves the destination")); } let skip = (o - cursor) as usize; let (_, tail) = std::mem::take(&mut rest).split_at_mut(skip); @@ -65,65 +84,121 @@ pub fn load_experts_ranges( rest = tail; cursor = o + n; } - let windows: Vec>> = windows.into_iter().map(Mutex::new).collect(); - let next = AtomicUsize::new(0); - let read_ns = AtomicU64::new(0); - let copy_ns = AtomicU64::new(0); - let error: Mutex> = Mutex::new(None); - let hashes: Vec = (0..layer_off.len()).map(|_| AtomicU64::new(FNV_SEED)).collect(); + Ok(windows.into_iter().map(std::sync::Mutex::new).collect()) +} + +/// What the load workers share: the layers still to take, their timers, the first error and the layer hashes. +#[cfg(unix)] +struct LoadShared<'a> { + windows: LayerWindows<'a>, + next: std::sync::atomic::AtomicUsize, + read_ns: std::sync::atomic::AtomicU64, + copy_ns: std::sync::atomic::AtomicU64, + error: std::sync::Mutex>, + hashes: Vec, +} + +/// Read and copy time of the layers one worker finished, in nanoseconds. +#[cfg(unix)] +#[derive(Default)] +struct WorkerTimers { + read: u64, + copy: u64, +} + +#[cfg(unix)] +impl LoadShared<'_> { + fn fill(&self, st: &mut LoadStats) { + use std::sync::atomic::Ordering; + st.read_seconds = self.read_ns.load(Ordering::Relaxed) as f64 / 1e9; + st.copy_seconds = self.copy_ns.load(Ordering::Relaxed) as f64 / 1e9; + st.layer_checksums = self.hashes.iter().map(|h| h.load(Ordering::Relaxed)).collect(); + } +} + +/// Runs `threads` workers over the layers; the first error any of them reports fails the load. +#[cfg(unix)] +fn run_workers<'a>( + path: &std::path::Path, + windows: LayerWindows<'a>, + threads: usize, + chunk: u64, +) -> Result, String> { + use std::sync::atomic::{AtomicU64, AtomicUsize}; + let hashes = (0..windows.len()).map(|_| AtomicU64::new(FNV_SEED)).collect(); + let mut shared = LoadShared { + windows, + next: AtomicUsize::new(0), + read_ns: AtomicU64::new(0), + copy_ns: AtomicU64::new(0), + error: std::sync::Mutex::new(None), + hashes, + }; std::thread::scope(|scope| { for _ in 0..threads { - scope.spawn(|| { - let file = match std::fs::File::open(path) { - Ok(f) => f, - Err(_) => { - *error.lock().unwrap() = Some(format!("cannot open {}", path.display())); - return; - } - }; - let mut buf = vec![0u8; chunk as usize]; - let (mut read_local, mut copy_local) = (0u64, 0u64); - loop { - let l = next.fetch_add(1, Ordering::Relaxed); - if l >= windows.len() { - break; - } - let (off, window) = windows[l].lock().unwrap().take().expect("each layer is taken once"); - let mut pos = 0usize; - let mut h = FNV_SEED; - while pos < window.len() { - let n = (window.len() - pos).min(chunk as usize); - let t_read = Instant::now(); - let got = read_up_to(&file, &mut buf[..n], off + pos as u64); - read_local += t_read.elapsed().as_nanos() as u64; - if got != n { - *error.lock().unwrap() = Some(format!( - "short read in layer {l}: got {got} of {n} B at offset {}", - off + pos as u64 - )); - return; - } - let t_copy = Instant::now(); - window[pos..pos + n].copy_from_slice(&buf[..n]); - h = fnv1a64(&buf[..n], h); - copy_local += t_copy.elapsed().as_nanos() as u64; - pos += n; - } - hashes[l].store(h, Ordering::Relaxed); - } - read_ns.fetch_add(read_local, Ordering::Relaxed); - copy_ns.fetch_add(copy_local, Ordering::Relaxed); - }); + scope.spawn(|| load_worker(&shared, path, chunk)); } }); - if let Some(message) = error.into_inner().unwrap() { - return fail(st, message); + match shared.error.get_mut().unwrap().take() { + Some(message) => Err(message), + None => Ok(shared), } - st.read_seconds = read_ns.load(Ordering::Relaxed) as f64 / 1e9; - st.copy_seconds = copy_ns.load(Ordering::Relaxed) as f64 / 1e9; - st.layer_checksums = hashes.iter().map(|h| h.load(Ordering::Relaxed)).collect(); - st.seconds = t0.elapsed().as_secs_f64(); - st +} + +#[cfg(unix)] +fn load_worker(shared: &LoadShared<'_>, path: &std::path::Path, chunk: u64) { + use std::sync::atomic::Ordering; + let Ok(file) = std::fs::File::open(path) else { + *shared.error.lock().unwrap() = Some(format!("cannot open {}", path.display())); + return; + }; + let mut buf = vec![0u8; chunk as usize]; + let mut timers = WorkerTimers::default(); + loop { + let l = shared.next.fetch_add(1, Ordering::Relaxed); + if l >= shared.windows.len() { + break; + } + let (off, window) = shared.windows[l].lock().unwrap().take().expect("each layer is taken once"); + match read_layer(&file, &mut buf, (l, off), window, &mut timers) { + Ok(hash) => shared.hashes[l].store(hash, Ordering::Relaxed), + Err(message) => { + *shared.error.lock().unwrap() = Some(message); + return; + } + } + } + shared.read_ns.fetch_add(timers.read, Ordering::Relaxed); + shared.copy_ns.fetch_add(timers.copy, Ordering::Relaxed); +} + +/// Reads one layer chunk by chunk into its window; returns the FNV-1a of the layer. A short read is an error. +#[cfg(unix)] +fn read_layer( + file: &std::fs::File, + buf: &mut [u8], + (l, off): (usize, u64), + window: &mut [u8], + timers: &mut WorkerTimers, +) -> Result { + use std::time::Instant; + let mut pos = 0usize; + let mut h = FNV_SEED; + while pos < window.len() { + let n = (window.len() - pos).min(buf.len()); + let t_read = Instant::now(); + let got = read_up_to(file, &mut buf[..n], off + pos as u64); + timers.read += t_read.elapsed().as_nanos() as u64; + if got != n { + return Err(format!("short read in layer {l}: got {got} of {n} B at offset {}", off + pos as u64)); + } + let t_copy = Instant::now(); + window[pos..pos + n].copy_from_slice(&buf[..n]); + h = fnv1a64(&buf[..n], h); + timers.copy += t_copy.elapsed().as_nanos() as u64; + pos += n; + } + Ok(h) } #[cfg(unix)] pub(super) fn read_up_to(file: &std::fs::File, buf: &mut [u8], offset: u64) -> usize { diff --git a/crates/model-format/src/ple_reader/impl_pagesource_for_file.rs b/crates/model-format/src/ple_reader/impl_pagesource_for_file.rs index eadfc008..fccb98d6 100644 --- a/crates/model-format/src/ple_reader/impl_pagesource_for_file.rs +++ b/crates/model-format/src/ple_reader/impl_pagesource_for_file.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: impl PageSource_for_File, impl fmt_Display_for, impl std_error_Error, fn err, impl PleReaderConfig, impl ReaderStats .... +//! Moved out of the parent module by STRA-338: impl PageSource_for_File, impl fmt_Display_for, impl std_error_Error, fn +//! err, impl PleReaderConfig, impl ReaderStats .... #[allow(unused_imports)] use super::*; @@ -138,33 +139,64 @@ pub fn plan_reads( for (i, &row) in rows.iter().enumerate() { let dst = &mut out[i * rb..(i + 1) * rb]; stats.requests += 1; - if u64::from(row) >= cfg.n_rows { - dst.fill(0); + if resolve_without_read(row, dst, cfg, cache, stats) { continue; } - if let Some(hit) = cache.find(row) { - dst.copy_from_slice(hit); - stats.cache_hits += 1; - continue; - } - let at = cfg.table_offset + u64::from(row) * rb as u64; - let first = at / PAGE as u64 * PAGE as u64; - let length = ((at + rb as u64 - 1) / PAGE as u64 * PAGE as u64 - first) as usize + PAGE; - let used = Use { row, in_page: (at - first) as usize, slot: i }; - if let Some(&j) = by_page.get(&first) { - jobs[j].length = jobs[j].length.max(length); - jobs[j].uses.push(used); - stats.dedup_rows += 1; - } else { - by_page.insert(first, jobs.len()); - jobs.push(PlannedRead { offset: first, length, uses: vec![used] }); - } + let (first, length, used) = locate_row(cfg, row, i); + merge_read(&mut by_page, &mut jobs, (first, length), used, stats); } // Sorted by offset: prefill chunks then read the SSD in near-sequential order. jobs.sort_by_key(|job| job.offset); jobs } +/// A row outside the table reads as zeros and a cached row is copied; neither needs a read (true). +fn resolve_without_read( + row: u32, + dst: &mut [u8], + cfg: &PleReaderConfig, + cache: &RowCache, + stats: &mut ReaderStats, +) -> bool { + if u64::from(row) >= cfg.n_rows { + dst.fill(0); + return true; + } + if let Some(hit) = cache.find(row) { + dst.copy_from_slice(hit); + stats.cache_hits += 1; + return true; + } + false +} + +/// (first page offset, read length, use) of a row that has to be read; the length is two pages when the row straddles. +fn locate_row(cfg: &PleReaderConfig, row: u32, slot: usize) -> (u64, usize, Use) { + let rb = cfg.row_bytes; + let at = cfg.table_offset + u64::from(row) * rb as u64; + let first = at / PAGE as u64 * PAGE as u64; + let length = ((at + rb as u64 - 1) / PAGE as u64 * PAGE as u64 - first) as usize + PAGE; + (first, length, Use { row, in_page: (at - first) as usize, slot }) +} + +/// Adds the use to the read of its first page (widening it if needed), or starts a read for that page. +fn merge_read( + by_page: &mut HashMap, + jobs: &mut Vec, + (first, length): (u64, usize), + used: Use, + stats: &mut ReaderStats, +) { + if let Some(&j) = by_page.get(&first) { + jobs[j].length = jobs[j].length.max(length); + jobs[j].uses.push(used); + stats.dedup_rows += 1; + } else { + by_page.insert(first, jobs.len()); + jobs.push(PlannedRead { offset: first, length, uses: vec![used] }); + } +} + pub(super) fn lock(m: &Mutex) -> MutexGuard<'_, State> { // A panicking worker must not wedge the reader: the data is still coherent // (every mutation is completed before the lock is released) and the error diff --git a/crates/model-format/src/ple_reader/impl_plereader.rs b/crates/model-format/src/ple_reader/impl_plereader.rs index dc04f15d..988aaa8a 100644 --- a/crates/model-format/src/ple_reader/impl_plereader.rs +++ b/crates/model-format/src/ple_reader/impl_plereader.rs @@ -8,43 +8,13 @@ impl PleReader { /// `table_offset` (the caller's GGUF parse checks that; the length is /// checked here too). pub fn open(source: Arc, cfg: PleReaderConfig) -> Result { - if cfg.max_inflight == 0 || cfg.max_inflight > 1024 { - return err("max_inflight must be 1..1024"); - } - if cfg.row_bytes == 0 || cfg.row_bytes > PAGE { - return err("row_bytes must be 1..4096"); - } - if cfg.n_rows > u64::from(EMPTY) { - return err("the row count exceeds the 32-bit row index"); - } - let table_end = - cfg.n_rows.checked_mul(cfg.row_bytes as u64).and_then(|bytes| bytes.checked_add(cfg.table_offset)); - let len = source.len().map_err(|e| PleError(format!("PleReader: cannot size the table file ({e})")))?; - if table_end.is_none_or(|end| end > len) { - return err("the table extends past the end of the file"); - } - if cfg.expected_len.is_some_and(|expected| expected != len) { - return err("the table file changed size after verification"); - } + check_config(&cfg)?; + check_table(source.as_ref(), &cfg)?; let threads = match cfg.io_threads { None => cfg.max_inflight.min(DEFAULT_IO_THREADS), Some(n) => n.min(cfg.max_inflight), }; - let seed = 0x9E37_79B9_7F4A_7C15 - ^ std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(1, |d| d.as_micros() as u64); - let state = State { - queue: VecDeque::new(), - tickets: HashMap::new(), - next_ticket: 1, - cache: RowCache::new(cfg.cache_rows, cfg.row_bytes), - stats: ReaderStats::default(), - ring_pos: 0, - delay: Duration::ZERO, - error: None, - stop: false, - inflight: 0, - keep: KeepAlive { rng: if seed == 0 { 1 } else { seed }, ..KeepAlive::default() }, - }; + let state = initial_state(&cfg); let shared = Arc::new(Shared { source, inline: threads == 0, @@ -89,14 +59,7 @@ impl PleReader { let mut out = vec![0u8; rows.len() * rb]; let State { cache, stats, .. } = &mut *st; let reads = plan_reads(rows, &shared.cfg, cache, &mut out, stats); - let mut pending = reads.len(); - if st.error.is_some() { - pending = 0; // the reader failed: `collect` reports it, nothing is queued - } else { - for read in reads { - st.queue.push_back(Job { read, ticket: id, keepalive: false }); - } - } + let pending = st.enqueue(reads, id); st.tickets.insert(id, TicketState { pending, out }); drop(st); if pending > 0 { @@ -119,39 +82,14 @@ impl PleReader { if !st.tickets.contains_key(&ticket.id) { return err("unknown ticket"); } - loop { - let pending = st.tickets.get(&ticket.id).map_or(0, |t| t.pending); - if pending == 0 { - break; - } - if shared.inline { - // No workers: this thread performs the reads itself. - if let Some((job, issued, delay)) = shared.start(&mut st) { - drop(st); - shared.run(job, issued, delay); - st = lock(&shared.state); - continue; - } - } - st = shared.done.wait(st).unwrap_or_else(|p| p.into_inner()); - } + st = shared.wait_for_ticket(st, ticket.id); if let Some(e) = st.error.clone() { return Err(e); } st.stats.wait_us += start.elapsed().as_secs_f64() * 1e6; let out = st.tickets.remove(&ticket.id).map(|t| t.out); drop(st); - // The same-FD size observation the verified GGUF reader makes around its streams. - if let Some(expected) = shared.cfg.expected_len { - match shared.source.len() { - Ok(len) if len == expected => {} - _ => { - let mut st = lock(&shared.state); - st.fail("the table file changed size after verification"); - return Err(st.error.clone().unwrap_or_else(|| PleError("PleReader: size check failed".into()))); - } - } - } + shared.check_expected_len()?; out.ok_or_else(|| PleError("PleReader: unknown ticket".into())) } @@ -225,3 +163,47 @@ impl PleReader { } } } + +fn check_config(cfg: &PleReaderConfig) -> Result<(), PleError> { + if cfg.max_inflight == 0 || cfg.max_inflight > 1024 { + return err("max_inflight must be 1..1024"); + } + if cfg.row_bytes == 0 || cfg.row_bytes > PAGE { + return err("row_bytes must be 1..4096"); + } + if cfg.n_rows > u64::from(EMPTY) { + return err("the row count exceeds the 32-bit row index"); + } + Ok(()) +} + +/// The table fits in the file from `table_offset`, and the file is the size it was verified at. +fn check_table(source: &S, cfg: &PleReaderConfig) -> Result<(), PleError> { + let table_end = cfg.n_rows.checked_mul(cfg.row_bytes as u64).and_then(|bytes| bytes.checked_add(cfg.table_offset)); + let len = source.len().map_err(|e| PleError(format!("PleReader: cannot size the table file ({e})")))?; + if table_end.is_none_or(|end| end > len) { + return err("the table extends past the end of the file"); + } + if cfg.expected_len.is_some_and(|expected| expected != len) { + return err("the table file changed size after verification"); + } + Ok(()) +} + +fn initial_state(cfg: &PleReaderConfig) -> State { + let seed = 0x9E37_79B9_7F4A_7C15 + ^ std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(1, |d| d.as_micros() as u64); + State { + queue: VecDeque::new(), + tickets: HashMap::new(), + next_ticket: 1, + cache: RowCache::new(cfg.cache_rows, cfg.row_bytes), + stats: ReaderStats::default(), + ring_pos: 0, + delay: Duration::ZERO, + error: None, + stop: false, + inflight: 0, + keep: KeepAlive { rng: if seed == 0 { 1 } else { seed }, ..KeepAlive::default() }, + } +} diff --git a/crates/model-format/src/ple_reader/impl_state.rs b/crates/model-format/src/ple_reader/impl_state.rs index 6394da43..b431a6dd 100644 --- a/crates/model-format/src/ple_reader/impl_state.rs +++ b/crates/model-format/src/ple_reader/impl_state.rs @@ -22,6 +22,19 @@ impl State { } } + /// Queues the reads of a ticket; returns how many it now waits for (none once the reader has failed: + /// `collect` reports the error and nothing is queued). + pub(super) fn enqueue(&mut self, reads: Vec, ticket: u32) -> usize { + if self.error.is_some() { + return 0; + } + let pending = reads.len(); + for read in reads { + self.queue.push_back(Job { read, ticket, keepalive: false }); + } + pending + } + pub(super) fn release(&mut self, ticket: u32) { if let Some(t) = self.tickets.get_mut(&ticket) { t.pending = t.pending.saturating_sub(1); @@ -35,6 +48,45 @@ impl State { self.cancel_queued(); } + /// A keep-alive read finished: a failure turns the keep-alive off, not the reader. + pub(super) fn finish_keepalive(&mut self, read: io::Result, elapsed_us: f64) { + match read { + Ok(_) => { + self.stats.keepalive_reads += 1; + self.stats.keepalive_us_max = self.stats.keepalive_us_max.max(elapsed_us); + } + Err(_) => self.keep.period = Duration::ZERO, + } + } + + /// A ticket read finished: its rows go to the ticket and the cache, or the reader fails; the ticket is released. + pub(super) fn finish_read(&mut self, job: &Job, read: io::Result, elapsed_us: f64, data: (&[u8], usize)) { + match read { + Err(e) => self.fail(&format!("a table read failed ({e})")), + Ok(bytes) => { + self.record_latency(elapsed_us); + self.stats.bytes += bytes as u64; + if job.read.uses.iter().any(|u| u.in_page + data.1 > bytes) { + self.fail("short read inside the table"); + } else { + self.store_rows(job, data); + } + } + } + self.release(job.ticket); + } + + /// Copies the rows of a finished read into the ticket's buffer and the cache. + fn store_rows(&mut self, job: &Job, (data, rb): (&[u8], usize)) { + for u in &job.read.uses { + let row = &data[u.in_page..u.in_page + rb]; + if let Some(t) = self.tickets.get_mut(&job.ticket) { + t.out[u.slot * rb..(u.slot + 1) * rb].copy_from_slice(row); + } + self.cache.insert(u.row, row); + } + } + /// When the next keep-alive read is due, or `None` when none is: it is off, /// the reader failed, or no rows were asked for within the window (the SSD /// may then sleep; the next `issue` re-arms it). @@ -53,20 +105,15 @@ impl Shared { pub(super) fn run(&self, job: Job, issued: Instant, delay: Duration) { let mut buf = AlignedBuf::new(2 * PAGE); let length = job.read.length; - // A source that panics is a failed read like any other: the worker survives, the reader fails and every ticket is released. - // Unwinding past this point would end the worker with the job's ticket still pending, and its `collect` would wait for ever. + // A source that panics is a failed read like any other: the worker survives, the reader fails and every ticket + // is released. + // Unwinding past this point would end the worker with the job's ticket still pending, and its `collect` would + // wait for ever. let read = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { read_full_at(self.source.as_ref(), buf.window(length), job.read.offset) })) .unwrap_or_else(|_| Err(io::Error::other("the page source panicked"))); - let mut late = false; - if !delay.is_zero() { - let spent = issued.elapsed(); - if spent < delay { - late = true; - thread::sleep(delay - spent); - } - } + let late = sleep_until_delay(issued, delay); let mut st = lock(&self.state); st.inflight -= 1; if late { @@ -74,49 +121,49 @@ impl Shared { } let elapsed_us = issued.elapsed().as_secs_f64() * 1e6; if job.keepalive { - // A failed keep-alive turns the keep-alive off, not the reader. - match read { - Ok(_) => { - st.stats.keepalive_reads += 1; - st.stats.keepalive_us_max = st.stats.keepalive_us_max.max(elapsed_us); - } - Err(_) => st.keep.period = Duration::ZERO, - } - drop(st); - self.work.notify_all(); - self.done.notify_all(); - return; - } - match read { - Err(e) => { - st.fail(&format!("a table read failed ({e})")); - st.release(job.ticket); - } - Ok(bytes) => { - st.record_latency(elapsed_us); - st.stats.bytes += bytes as u64; - let rb = self.cfg.row_bytes; - if job.read.uses.iter().any(|u| u.in_page + rb > bytes) { - st.fail("short read inside the table"); - st.release(job.ticket); - } else { - let data = buf.window(length); - for u in &job.read.uses { - let row = &data[u.in_page..u.in_page + rb]; - if let Some(t) = st.tickets.get_mut(&job.ticket) { - t.out[u.slot * rb..(u.slot + 1) * rb].copy_from_slice(row); - } - st.cache.insert(u.row, row); - } - st.release(job.ticket); - } - } + st.finish_keepalive(read, elapsed_us); + } else { + st.finish_read(&job, read, elapsed_us, (buf.window(length), self.cfg.row_bytes)); } drop(st); self.work.notify_all(); self.done.notify_all(); } + /// Waits until the ticket has no read pending. Without workers (`inline`) this thread performs the reads itself. + pub(super) fn wait_for_ticket<'a>(&'a self, mut st: MutexGuard<'a, State>, id: u32) -> MutexGuard<'a, State> { + loop { + let pending = st.tickets.get(&id).map_or(0, |t| t.pending); + if pending == 0 { + return st; + } + if self.inline + && let Some((job, issued, delay)) = self.start(&mut st) + { + drop(st); + self.run(job, issued, delay); + st = lock(&self.state); + continue; + } + st = self.done.wait(st).unwrap_or_else(|p| p.into_inner()); + } + } + + /// The same-FD size observation the verified GGUF reader makes around its streams. + pub(super) fn check_expected_len(&self) -> Result<(), PleError> { + let Some(expected) = self.cfg.expected_len else { + return Ok(()); + }; + match self.source.len() { + Ok(len) if len == expected => Ok(()), + _ => { + let mut st = lock(&self.state); + st.fail("the table file changed size after verification"); + Err(st.error.clone().unwrap_or_else(|| PleError("PleReader: size check failed".into()))) + } + } + } + /// Take the next job (marking it in flight) or `None` when there is none. pub(super) fn start(&self, st: &mut State) -> Option<(Job, Instant, Duration)> { let job = st.queue.pop_front()?; @@ -155,20 +202,7 @@ impl Shared { None => st = self.keep_cv.wait(st).unwrap_or_else(|p| p.into_inner()), Some(due) if now >= due => { if st.queue.is_empty() && st.inflight == 0 { - // One page of the table, a different one each time, so the - // SSD really reads (not its controller's buffer). - st.keep.rng ^= st.keep.rng << 13; - st.keep.rng ^= st.keep.rng >> 7; - st.keep.rng ^= st.keep.rng << 17; - let first = self.cfg.table_offset / PAGE as u64; - let end = (self.cfg.table_offset + self.cfg.n_rows * self.cfg.row_bytes as u64) / PAGE as u64; - let page = first + if end > first { st.keep.rng % (end - first) } else { 0 }; - st.queue.push_back(Job { - read: PlannedRead { offset: page * PAGE as u64, length: PAGE, uses: Vec::new() }, - ticket: 0, - keepalive: true, - }); - self.work.notify_one(); + self.queue_keepalive_page(&mut st); } // Re-evaluate after the period (or when woken). let wait = st.keep.period.max(Duration::from_millis(1)); @@ -181,6 +215,36 @@ impl Shared { } } } + + /// One page of the table, a different one each time, so the + /// SSD really reads (not its controller's buffer). + fn queue_keepalive_page(&self, st: &mut State) { + st.keep.rng ^= st.keep.rng << 13; + st.keep.rng ^= st.keep.rng >> 7; + st.keep.rng ^= st.keep.rng << 17; + let first = self.cfg.table_offset / PAGE as u64; + let end = (self.cfg.table_offset + self.cfg.n_rows * self.cfg.row_bytes as u64) / PAGE as u64; + let page = first + if end > first { st.keep.rng % (end - first) } else { 0 }; + st.queue.push_back(Job { + read: PlannedRead { offset: page * PAGE as u64, length: PAGE, uses: Vec::new() }, + ticket: 0, + keepalive: true, + }); + self.work.notify_one(); + } +} + +/// Fault injection: sleeps until `delay` has passed since `issued`; true when it had to sleep. +fn sleep_until_delay(issued: Instant, delay: Duration) -> bool { + if delay.is_zero() { + return false; + } + let spent = issued.elapsed(); + if spent >= delay { + return false; + } + thread::sleep(delay - spent); + true } impl Drop for Ticket { diff --git a/crates/model-format/src/ple_reader/tests.rs b/crates/model-format/src/ple_reader/tests.rs index 1d215f76..100459a9 100644 --- a/crates/model-format/src/ple_reader/tests.rs +++ b/crates/model-format/src/ple_reader/tests.rs @@ -79,10 +79,12 @@ fn cfg(offset: u64, rows: u64) -> PleReaderConfig { PleReaderConfig::new(offset, rows) } -// ---- a failed read never leaves a later ticket waiting (upstream ebe3383a: after a failed read the worker parked, `issue` kept +// ---- a failed read never leaves a later ticket waiting (upstream ebe3383a: after a failed read the worker parked, +// `issue` kept // queueing and the next `collect` blocked for ever). Every blocking call below runs on its own thread with a deadline. -/// Run `f` on a thread and return its result, or panic when it does not finish in five seconds (the hang this guards against). +/// Run `f` on a thread and return its result, or panic when it does not finish in five seconds (the hang this guards +/// against). fn within(what: &str, f: impl FnOnce() -> T + Send + 'static) -> T { let (tx, rx) = std::sync::mpsc::channel(); thread::spawn(move || { @@ -115,7 +117,8 @@ impl PageSource for Flaky { } } -/// Rows whose first page is page `page` of a table at offset 0 with 90-byte rows (row 45 = byte 4050 straddles pages 0 and 1). +/// Rows whose first page is page `page` of a table at offset 0 with 90-byte rows (row 45 = byte 4050 straddles pages 0 +/// and 1). fn row_on_page(page: u64) -> u32 { (page * PAGE as u64 / 90 + 1) as u32 } diff --git a/crates/model-format/src/ple_reader/tests/max_inflight_bounds_concurrent_reads.rs b/crates/model-format/src/ple_reader/tests/max_inflight_bounds_concurrent_reads.rs index 8345655f..fad90043 100644 --- a/crates/model-format/src/ple_reader/tests/max_inflight_bounds_concurrent_reads.rs +++ b/crates/model-format/src/ple_reader/tests/max_inflight_bounds_concurrent_reads.rs @@ -1,4 +1,6 @@ -//! Tests of tests by topic (moved out of the test file by STRA-338): max_inflight_bounds_concurrent_reads, keepalive_reads_a_table_page_when_idle_and_stops_after_the_window, a_failing_keepalive_turns_itself_off_not_the_reader, latency_ring_is_bounded .... +//! Tests of tests by topic (moved out of the test file by STRA-338): max_inflight_bounds_concurrent_reads, +//! keepalive_reads_a_table_page_when_idle_and_stops_after_the_window, +//! a_failing_keepalive_turns_itself_off_not_the_reader, latency_ring_is_bounded .... #[allow(unused_imports)] use super::*; diff --git a/crates/model-format/src/ple_reader/tests/rows_match_the_oracle_including.rs b/crates/model-format/src/ple_reader/tests/rows_match_the_oracle_including.rs index dd8fd2dd..d4a39a60 100644 --- a/crates/model-format/src/ple_reader/tests/rows_match_the_oracle_including.rs +++ b/crates/model-format/src/ple_reader/tests/rows_match_the_oracle_including.rs @@ -1,4 +1,6 @@ -//! Tests of tests by topic (moved out of the test file by STRA-338): rows_match_the_oracle_including_out_of_range, rows_on_one_page_share_one_read_and_straddlers_read_two_pages, a_later_straddler_widens_the_read_of_its_first_page, plan_is_sorted_by_offset_and_covers_every_missing_row_once .... +//! Tests of tests by topic (moved out of the test file by STRA-338): rows_match_the_oracle_including_out_of_range, +//! rows_on_one_page_share_one_read_and_straddlers_read_two_pages, a_later_straddler_widens_the_read_of_its_first_page, +//! plan_is_sorted_by_offset_and_covers_every_missing_row_once .... #[allow(unused_imports)] use super::*; diff --git a/crates/model-format/src/qwen4exp/expected_inventory.rs b/crates/model-format/src/qwen4exp/expected_inventory.rs index 78ece5af..e3ac8cd0 100644 --- a/crates/model-format/src/qwen4exp/expected_inventory.rs +++ b/crates/model-format/src/qwen4exp/expected_inventory.rs @@ -3,94 +3,111 @@ #[allow(unused_imports)] use super::*; +/// (role, name suffix, dimensions, GGUF kind pinned for it if any) of a tensor of every layer or of one family of +/// layers. +type LayerEntry = (LayerRole, &'static str, &'static [u64], Option); + +const GLOBAL_TENSORS: [(GlobalRole, &str, &[u64], Option); 5] = [ + (GlobalRole::TokenEmbedding, "token_embd.weight", &[2560, 248320], None), + (GlobalRole::Output, "output.weight", &[2560, 248320], None), + (GlobalRole::OutputHcDown, "output_hc_down.weight", &[10240, 320], None), + (GlobalRole::OutputHcNorm, "output_hc_norm.weight", &[10240], Some(0)), + (GlobalRole::OutputHcUp, "output_hc_up.weight", &[320, 10240], None), +]; + +const COMMON_LAYER_TENSORS: [LayerEntry; 16] = [ + (LayerRole::HcAttnDown, "hc_attn_down.weight", &[10240, 320], None), + (LayerRole::HcAttnUp, "hc_attn_up.weight", &[320, 10240], None), + (LayerRole::HcAttnInject, "hc_attn_inject.weight", &[10240, 4], None), + (LayerRole::HcAttnNorm, "hc_attn_norm.weight", &[10240], Some(0)), + (LayerRole::HcFfnDown, "hc_ffn_down.weight", &[10240, 320], None), + (LayerRole::HcFfnUp, "hc_ffn_up.weight", &[320, 10240], None), + (LayerRole::HcFfnInject, "hc_ffn_inject.weight", &[10240, 4], None), + (LayerRole::HcFfnNorm, "hc_ffn_norm.weight", &[10240], Some(0)), + (LayerRole::FfnGateInp, "ffn_gate_inp.weight", &[2560, 512], Some(30)), + (LayerRole::FfnGateInpShared, "ffn_gate_inp_shexp.weight", &[2560], Some(30)), + (LayerRole::FfnGateShared, "ffn_gate_shexp.weight", &[2560, 640], None), + (LayerRole::FfnUpShared, "ffn_up_shexp.weight", &[2560, 640], None), + (LayerRole::FfnDownShared, "ffn_down_shexp.weight", &[640, 2560], None), + (LayerRole::FfnGateExperts, "ffn_gate_exps.weight", &[2560, 640, 512], None), + (LayerRole::FfnUpExperts, "ffn_up_exps.weight", &[2560, 640, 512], None), + (LayerRole::FfnDownExperts, "ffn_down_exps.weight", &[640, 2560, 512], None), +]; + +/// The tensors of the layers with full attention (every fourth layer). +const FULL_ATTENTION_TENSORS: [LayerEntry; 10] = [ + (LayerRole::AttnQ, "attn_q.weight", &[2560, 12288], None), + (LayerRole::AttnK, "attn_k.weight", &[2560, 512], None), + (LayerRole::AttnV, "attn_v.weight", &[2560, 512], None), + (LayerRole::AttnOutput, "attn_output.weight", &[6144, 2560], None), + (LayerRole::AttnQNorm, "attn_q_norm.weight", &[256], Some(0)), + (LayerRole::AttnKNorm, "attn_k_norm.weight", &[256], Some(0)), + (LayerRole::IndexerQProj, "indexer.q_proj.weight", &[2560, 512], None), + (LayerRole::IndexerKProj, "indexer.k_proj.weight", &[2560, 128], None), + (LayerRole::IndexerQNorm, "indexer.q_norm.weight", &[128], Some(0)), + (LayerRole::IndexerKNorm, "indexer.k_norm.weight", &[128], Some(0)), +]; + +/// The tensors of the layers with linear attention (the SSM family). +const LINEAR_ATTENTION_TENSORS: [LayerEntry; 9] = [ + (LayerRole::AttnQkv, "attn_qkv.weight", &[2560, 10240], None), + (LayerRole::AttnGate, "attn_gate.weight", &[2560, 6144], None), + (LayerRole::SsmOut, "ssm_out.weight", &[6144, 2560], None), + (LayerRole::SsmConv1d, "ssm_conv1d.weight", &[4, 10240], None), + (LayerRole::SsmAlpha, "ssm_alpha.weight", &[2560, 48], None), + (LayerRole::SsmBeta, "ssm_beta.weight", &[2560, 48], None), + (LayerRole::SsmA, "ssm_a", &[48], Some(0)), + (LayerRole::SsmDtBias, "ssm_dt.bias", &[48], Some(0)), + (LayerRole::SsmNorm, "ssm_norm.weight", &[128], Some(0)), +]; + +/// The extra tensors of layer 1. +const PLE_LAYER_TENSORS: [LayerEntry; 6] = [ + (LayerRole::PleConv1d, "ple_conv1d.weight", &[4, 10240], Some(1)), + (LayerRole::PleKey, "ple_key.weight", &[2560, 10240], Some(30)), + (LayerRole::PleNormConv, "ple_norm_conv.weight", &[10240], Some(0)), + (LayerRole::PleNormKey, "ple_norm_key.weight", &[10240], Some(0)), + (LayerRole::PleNormQuery, "ple_norm_query.weight", &[10240], Some(0)), + (LayerRole::PleValue, "ple_value.weight", &[2560, 2560], Some(30)), +]; + +/// The gate, up and down routed-expert tensors of every layer, in layer order. +pub(super) fn expert_roles() -> impl Iterator { + (0..48).flat_map(|layer| { + [LayerRole::FfnGateExperts, LayerRole::FfnUpExperts, LayerRole::FfnDownExperts] + .map(|role| TensorRole::Layer { layer, role }) + }) +} + +fn expected_tensor(role: TensorRole, name: String, dimensions: &[u64], shard: u8, kind: Option) -> ExpectedTensor { + ExpectedTensor { role, name, dimensions: dimensions.to_vec(), shard, kind } +} + pub(super) fn expected_inventory() -> Vec { let mut expected = Vec::with_capacity(1224); - let mut add = |role, name: String, dimensions: &[u64], shard, kind| { - expected.push(ExpectedTensor { role, name, dimensions: dimensions.to_vec(), shard, kind }); - }; - for (role, name, dimensions, kind) in [ - (GlobalRole::TokenEmbedding, "token_embd.weight", &[2560, 248320][..], None), - (GlobalRole::Output, "output.weight", &[2560, 248320][..], None), - (GlobalRole::OutputHcDown, "output_hc_down.weight", &[10240, 320][..], None), - (GlobalRole::OutputHcNorm, "output_hc_norm.weight", &[10240][..], Some(0)), - (GlobalRole::OutputHcUp, "output_hc_up.weight", &[320, 10240][..], None), - ] { - add(TensorRole::Global(role), name.to_owned(), dimensions, 0, kind); + for &(role, name, dimensions, kind) in &GLOBAL_TENSORS { + expected.push(expected_tensor(TensorRole::Global(role), name.to_owned(), dimensions, 0, kind)); } - add( + expected.push(expected_tensor( TensorRole::Global(GlobalRole::PerLayerTokenEmbedding), "per_layer_token_embd.weight".to_owned(), &[160, 320_001_536], 1, Some(20), - ); - + )); for layer in 0..48u8 { - let prefix = format!("blk.{layer}."); - let common = [ - (LayerRole::HcAttnDown, "hc_attn_down.weight", &[10240, 320][..], None), - (LayerRole::HcAttnUp, "hc_attn_up.weight", &[320, 10240][..], None), - (LayerRole::HcAttnInject, "hc_attn_inject.weight", &[10240, 4][..], None), - (LayerRole::HcAttnNorm, "hc_attn_norm.weight", &[10240][..], Some(0)), - (LayerRole::HcFfnDown, "hc_ffn_down.weight", &[10240, 320][..], None), - (LayerRole::HcFfnUp, "hc_ffn_up.weight", &[320, 10240][..], None), - (LayerRole::HcFfnInject, "hc_ffn_inject.weight", &[10240, 4][..], None), - (LayerRole::HcFfnNorm, "hc_ffn_norm.weight", &[10240][..], Some(0)), - (LayerRole::FfnGateInp, "ffn_gate_inp.weight", &[2560, 512][..], Some(30)), - (LayerRole::FfnGateInpShared, "ffn_gate_inp_shexp.weight", &[2560][..], Some(30)), - (LayerRole::FfnGateShared, "ffn_gate_shexp.weight", &[2560, 640][..], None), - (LayerRole::FfnUpShared, "ffn_up_shexp.weight", &[2560, 640][..], None), - (LayerRole::FfnDownShared, "ffn_down_shexp.weight", &[640, 2560][..], None), - (LayerRole::FfnGateExperts, "ffn_gate_exps.weight", &[2560, 640, 512][..], None), - (LayerRole::FfnUpExperts, "ffn_up_exps.weight", &[2560, 640, 512][..], None), - (LayerRole::FfnDownExperts, "ffn_down_exps.weight", &[640, 2560, 512][..], None), - ]; - for (role, name, dimensions, kind) in common { - add(TensorRole::Layer { layer, role }, format!("{prefix}{name}"), dimensions, 0, kind); - } - let family = if layer % 4 == 3 { - [ - (LayerRole::AttnQ, "attn_q.weight", &[2560, 12288][..], None), - (LayerRole::AttnK, "attn_k.weight", &[2560, 512][..], None), - (LayerRole::AttnV, "attn_v.weight", &[2560, 512][..], None), - (LayerRole::AttnOutput, "attn_output.weight", &[6144, 2560][..], None), - (LayerRole::AttnQNorm, "attn_q_norm.weight", &[256][..], Some(0)), - (LayerRole::AttnKNorm, "attn_k_norm.weight", &[256][..], Some(0)), - (LayerRole::IndexerQProj, "indexer.q_proj.weight", &[2560, 512][..], None), - (LayerRole::IndexerKProj, "indexer.k_proj.weight", &[2560, 128][..], None), - (LayerRole::IndexerQNorm, "indexer.q_norm.weight", &[128][..], Some(0)), - (LayerRole::IndexerKNorm, "indexer.k_norm.weight", &[128][..], Some(0)), - ] - .to_vec() - } else { - [ - (LayerRole::AttnQkv, "attn_qkv.weight", &[2560, 10240][..], None), - (LayerRole::AttnGate, "attn_gate.weight", &[2560, 6144][..], None), - (LayerRole::SsmOut, "ssm_out.weight", &[6144, 2560][..], None), - (LayerRole::SsmConv1d, "ssm_conv1d.weight", &[4, 10240][..], None), - (LayerRole::SsmAlpha, "ssm_alpha.weight", &[2560, 48][..], None), - (LayerRole::SsmBeta, "ssm_beta.weight", &[2560, 48][..], None), - (LayerRole::SsmA, "ssm_a", &[48][..], Some(0)), - (LayerRole::SsmDtBias, "ssm_dt.bias", &[48][..], Some(0)), - (LayerRole::SsmNorm, "ssm_norm.weight", &[128][..], Some(0)), - ] - .to_vec() - }; - for (role, name, dimensions, kind) in family { - add(TensorRole::Layer { layer, role }, format!("{prefix}{name}"), dimensions, 0, kind); - } - if layer == 1 { - for (role, name, dimensions, kind) in [ - (LayerRole::PleConv1d, "ple_conv1d.weight", &[4, 10240][..], Some(1)), - (LayerRole::PleKey, "ple_key.weight", &[2560, 10240][..], Some(30)), - (LayerRole::PleNormConv, "ple_norm_conv.weight", &[10240][..], Some(0)), - (LayerRole::PleNormKey, "ple_norm_key.weight", &[10240][..], Some(0)), - (LayerRole::PleNormQuery, "ple_norm_query.weight", &[10240][..], Some(0)), - (LayerRole::PleValue, "ple_value.weight", &[2560, 2560][..], Some(30)), - ] { - add(TensorRole::Layer { layer, role }, format!("{prefix}{name}"), dimensions, 0, kind); - } - } + push_layer(&mut expected, layer); } expected } + +/// The tensors of one layer: the common ones, the attention family of the layer, and the PLE ones of layer 1. +fn push_layer(expected: &mut Vec, layer: u8) { + let prefix = format!("blk.{layer}."); + let family: &[LayerEntry] = if layer % 4 == 3 { &FULL_ATTENTION_TENSORS } else { &LINEAR_ATTENTION_TENSORS }; + let extra: &[LayerEntry] = if layer == 1 { &PLE_LAYER_TENSORS } else { &[] }; + for &(role, name, dimensions, kind) in COMMON_LAYER_TENSORS.iter().chain(family).chain(extra) { + let role = TensorRole::Layer { layer, role }; + expected.push(expected_tensor(role, format!("{prefix}{name}"), dimensions, 0, kind)); + } +} diff --git a/crates/model-format/src/qwen4exp/impl_fmt_display_for.rs b/crates/model-format/src/qwen4exp/impl_fmt_display_for.rs index 23a1399a..6396ae91 100644 --- a/crates/model-format/src/qwen4exp/impl_fmt_display_for.rs +++ b/crates/model-format/src/qwen4exp/impl_fmt_display_for.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: impl fmt_Display_for, impl Error_for_BindingError, impl Qwen4ExpTopology, impl ResolvedTensor. +//! Moved out of the parent module by STRA-338: impl fmt_Display_for, impl Error_for_BindingError, impl +//! Qwen4ExpTopology, impl ResolvedTensor. #[allow(unused_imports)] use super::*; diff --git a/crates/model-format/src/qwen4exp/impl_qwen4expartifact.rs b/crates/model-format/src/qwen4exp/impl_qwen4expartifact.rs index ebd26d41..354434b3 100644 --- a/crates/model-format/src/qwen4exp/impl_qwen4expartifact.rs +++ b/crates/model-format/src/qwen4exp/impl_qwen4expartifact.rs @@ -17,26 +17,8 @@ impl Qwen4ExpArtifact { pub(super) fn bind_after_identity(owners: [VerifiedGgufFile; 2]) -> Result { let mut owners = owners; - validate_owner_index_split(&owners)?; - let split_metadata = [ - owners[0].split_snapshot().map_err(BindingError::Io)?, - owners[1].split_snapshot().map_err(BindingError::Io)?, - ]; - validate_owner_metadata_split(&split_metadata)?; - let mut snapshots = [ - owners[0].profile_snapshot().map_err(BindingError::Io)?, - owners[1].profile_snapshot().map_err(BindingError::Io)?, - ]; - // Profile/topology admission precedes tokenizer parsing and validation. - if snapshots[0].architecture.as_deref() != Some("qwen4exp") { - return Err(BindingError::Metadata("general.architecture")); - } - if snapshots[1].architecture.as_deref().is_some_and(|value| value != "qwen4exp") { - return Err(BindingError::Metadata("general.architecture")); - } - topology(&snapshots[0])?; - snapshots[0].tokenizer = owners[0].tokenizer_snapshot().map_err(BindingError::Io)?; - let [metadata0, metadata1] = snapshots; + check_owner_split(&mut owners)?; + let [metadata0, metadata1] = read_profile_snapshots(&mut owners)?; let views = [ LogicalShardView { index: owners[0].index(), metadata: metadata0 }, LogicalShardView { index: owners[1].index(), metadata: metadata1 }, @@ -194,3 +176,29 @@ impl Qwen4ExpArtifact { .map_err(BindingError::Io) } } + +/// Both shards say they are the two halves of the split, in the index and in the split metadata. +fn check_owner_split(owners: &mut [VerifiedGgufFile; 2]) -> Result<(), BindingError> { + validate_owner_index_split(owners)?; + let split_metadata = + [owners[0].split_snapshot().map_err(BindingError::Io)?, owners[1].split_snapshot().map_err(BindingError::Io)?]; + validate_owner_metadata_split(&split_metadata) +} + +/// The profile snapshots of both shards, with the tokenizer of shard 0. +fn read_profile_snapshots(owners: &mut [VerifiedGgufFile; 2]) -> Result<[MetadataSnapshot; 2], BindingError> { + let mut snapshots = [ + owners[0].profile_snapshot().map_err(BindingError::Io)?, + owners[1].profile_snapshot().map_err(BindingError::Io)?, + ]; + // Profile/topology admission precedes tokenizer parsing and validation. + if snapshots[0].architecture.as_deref() != Some("qwen4exp") { + return Err(BindingError::Metadata("general.architecture")); + } + if snapshots[1].architecture.as_deref().is_some_and(|value| value != "qwen4exp") { + return Err(BindingError::Metadata("general.architecture")); + } + topology(&snapshots[0])?; + snapshots[0].tokenizer = owners[0].tokenizer_snapshot().map_err(BindingError::Io)?; + Ok(snapshots) +} diff --git a/crates/model-format/src/qwen4exp/plan_stream_rows.rs b/crates/model-format/src/qwen4exp/plan_stream_rows.rs index 24c31db1..ef9d87e4 100644 --- a/crates/model-format/src/qwen4exp/plan_stream_rows.rs +++ b/crates/model-format/src/qwen4exp/plan_stream_rows.rs @@ -3,6 +3,60 @@ #[allow(unused_imports)] use super::*; +/// (columns, rows, routed) of the one complete matrix a role may stream whole. +type MatrixShape = (u64, u64, bool); + +/// Layer roles that stream as one whole matrix, by shape: (roles, columns, rows, routed per expert). +const LAYER_MATRIX_SHAPES: &[(&[LayerRole], u64, u64, bool)] = &[ + (&[LayerRole::FfnGateExperts, LayerRole::FfnUpExperts], 2560, 640, true), + (&[LayerRole::FfnDownExperts], 640, 2560, true), + (&[LayerRole::FfnGateShared, LayerRole::FfnUpShared], 2560, 640, false), + (&[LayerRole::FfnDownShared], 640, 2560, false), + (&[LayerRole::AttnQkv], 2560, 10240, false), + (&[LayerRole::AttnGate], 2560, 6144, false), + (&[LayerRole::SsmConv1d], 4, 10240, false), + (&[LayerRole::SsmOut, LayerRole::AttnOutput], 6144, 2560, false), + (&[LayerRole::AttnQ], 2560, 12288, false), + (&[LayerRole::AttnK, LayerRole::AttnV, LayerRole::IndexerQProj, LayerRole::FfnGateInp], 2560, 512, false), + (&[LayerRole::IndexerKProj], 2560, 128, false), + (&[LayerRole::HcAttnDown, LayerRole::HcFfnDown], 10240, 320, false), + (&[LayerRole::HcAttnUp, LayerRole::HcFfnUp], 320, 10240, false), +]; + +/// The shape of the whole matrix a role may stream, if it has one. +fn matrix_shape(tensor: &ResolvedTensor, role: TensorRole) -> Option { + match role { + TensorRole::Layer { layer, role } => layer_matrix_shape(layer, role, tensor.kind), + TensorRole::Global(role) => global_matrix_shape(role), + } +} + +fn layer_matrix_shape(layer: u8, role: LayerRole, kind: u32) -> Option { + let ple = match (layer, role, kind) { + (1, LayerRole::PleKey, 30) => Some((2560, 10240, false)), + (1, LayerRole::PleValue, 30) => Some((2560, 2560, false)), + (1, LayerRole::PleConv1d, 1) => Some((4, 10240, false)), + _ => None, + }; + ple.or_else(|| { + LAYER_MATRIX_SHAPES + .iter() + .find(|entry| entry.0.contains(&role)) + .map(|&(_, columns, rows, routed)| (columns, rows, routed)) + }) +} + +fn global_matrix_shape(role: GlobalRole) -> Option { + match role { + GlobalRole::OutputHcDown => Some((10240, 320, false)), + GlobalRole::OutputHcUp => Some((320, 10240, false)), + // The complete vocabulary-major head / embedding table: the native head and embedding owners + // (`generate.cpp` NativeHead / embedding upload) read each as ONE whole-tensor stream. + GlobalRole::Output | GlobalRole::TokenEmbedding => Some((2560, 248320, false)), + _ => None, + } +} + /// Larger spans are restricted to one complete, source-defined matrix. /// Other roles and partial ranges retain the existing 64-row admission. pub(super) fn plan_stream_rows( @@ -15,39 +69,10 @@ pub(super) fn plan_stream_rows( if count <= 64 { return plan_rows(tensor, first, count, expert); } - use LayerRole as L; - let (columns, rows, routed) = match role { - TensorRole::Layer { role: L::FfnGateExperts | L::FfnUpExperts, .. } => (2560, 640, true), - TensorRole::Layer { role: L::FfnDownExperts, .. } => (640, 2560, true), - TensorRole::Layer { role: L::FfnGateShared | L::FfnUpShared, .. } => (2560, 640, false), - TensorRole::Layer { role: L::FfnDownShared, .. } => (640, 2560, false), - TensorRole::Layer { role: L::AttnQkv, .. } => (2560, 10240, false), - TensorRole::Layer { role: L::AttnGate, .. } => (2560, 6144, false), - TensorRole::Layer { role: L::SsmConv1d, .. } => (4, 10240, false), - TensorRole::Layer { layer: 1, role: L::PleKey } if tensor.kind == 30 => (2560, 10240, false), - TensorRole::Layer { layer: 1, role: L::PleValue } if tensor.kind == 30 => (2560, 2560, false), - TensorRole::Layer { layer: 1, role: L::PleConv1d } if tensor.kind == 1 => (4, 10240, false), - TensorRole::Layer { role: L::SsmOut | L::AttnOutput, .. } => (6144, 2560, false), - TensorRole::Layer { role: L::AttnQ, .. } => (2560, 12288, false), - TensorRole::Layer { role: L::AttnK | L::AttnV | L::IndexerQProj | L::FfnGateInp, .. } => (2560, 512, false), - TensorRole::Layer { role: L::IndexerKProj, .. } => (2560, 128, false), - TensorRole::Layer { role: L::HcAttnDown | L::HcFfnDown, .. } | TensorRole::Global(GlobalRole::OutputHcDown) => { - (10240, 320, false) - } - TensorRole::Layer { role: L::HcAttnUp | L::HcFfnUp, .. } | TensorRole::Global(GlobalRole::OutputHcUp) => { - (320, 10240, false) - } - // The complete vocabulary-major head / embedding table: the native head and embedding owners - // (`generate.cpp` NativeHead / embedding upload) read each as ONE whole-tensor stream. - TensorRole::Global(GlobalRole::Output | GlobalRole::TokenEmbedding) => (2560, 248320, false), - _ => return Err(BindingError::Range("row_count")), - }; + let (columns, rows, routed) = matrix_shape(tensor, role).ok_or(BindingError::Range("row_count"))?; let expected = [columns, rows, 512]; - if first != 0 - || count != rows - || expert.is_some() != routed - || tensor.dimensions != expected[..if routed { 3 } else { 2 }] - { + let rank = if routed { 3 } else { 2 }; + if first != 0 || count != rows || expert.is_some() != routed || tensor.dimensions != expected[..rank] { return Err(BindingError::Range("row_count")); } plan_row_span(tensor, first, count, expert) diff --git a/crates/model-format/src/qwen4exp/validate_logical_views.rs b/crates/model-format/src/qwen4exp/validate_logical_views.rs index f455be3b..6b287a52 100644 --- a/crates/model-format/src/qwen4exp/validate_logical_views.rs +++ b/crates/model-format/src/qwen4exp/validate_logical_views.rs @@ -6,25 +6,8 @@ use super::*; pub(super) fn validate_logical_views( mut shards: [LogicalShardView<'_>; 2], ) -> Result { - for (number, shard) in shards.iter().enumerate() { - let (expected_no, expected_count) = (number as u64, 2); - if shard.index.summary.split_no != Some(expected_no) || shard.metadata.split_no != Some(expected_no) { - return Err(BindingError::Split("split.no")); - } - if shard.index.summary.split_count != Some(expected_count) || shard.metadata.split_count != Some(expected_count) - { - return Err(BindingError::Split("split.count")); - } - if shard.index.summary.split_tensors_count != Some(1224) || shard.metadata.split_tensors_count != Some(1224) { - return Err(BindingError::Split("split.tensors.count")); - } - } - for (number, shard) in shards.iter().enumerate() { - let expected_tensors = if number == 0 { 1223 } else { 1 }; - if shard.index.tensors.len() != expected_tensors { - return Err(BindingError::Split("indexed_tensor_count")); - } - } + check_split_numbers(&shards)?; + check_tensor_counts(&shards)?; if shards[0].metadata.architecture.as_deref() != Some("qwen4exp") { return Err(BindingError::Metadata("general.architecture")); } @@ -40,3 +23,31 @@ pub(super) fn validate_logical_views( let roles = validate_role_inventory(&shards)?; Ok(ValidatedBindingView { topology, tokenizer, roles }) } + +/// Both the index and the metadata of each shard carry the split numbers of a two-shard model. +fn check_split_numbers(shards: &[LogicalShardView<'_>; 2]) -> Result<(), BindingError> { + for (number, shard) in shards.iter().enumerate() { + let (expected_no, expected_count) = (number as u64, 2); + if shard.index.summary.split_no != Some(expected_no) || shard.metadata.split_no != Some(expected_no) { + return Err(BindingError::Split("split.no")); + } + if shard.index.summary.split_count != Some(expected_count) || shard.metadata.split_count != Some(expected_count) + { + return Err(BindingError::Split("split.count")); + } + if shard.index.summary.split_tensors_count != Some(1224) || shard.metadata.split_tensors_count != Some(1224) { + return Err(BindingError::Split("split.tensors.count")); + } + } + Ok(()) +} + +fn check_tensor_counts(shards: &[LogicalShardView<'_>; 2]) -> Result<(), BindingError> { + for (number, shard) in shards.iter().enumerate() { + let expected_tensors = if number == 0 { 1223 } else { 1 }; + if shard.index.tensors.len() != expected_tensors { + return Err(BindingError::Split("indexed_tensor_count")); + } + } + Ok(()) +} diff --git a/crates/model-format/src/qwen4exp/validate_owner_index_split.rs b/crates/model-format/src/qwen4exp/validate_owner_index_split.rs index 8c2e4197..718030a8 100644 --- a/crates/model-format/src/qwen4exp/validate_owner_index_split.rs +++ b/crates/model-format/src/qwen4exp/validate_owner_index_split.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: fn validate_owner_index_split, fn validate_owner_metadata_split, fn required_uint, fn required_u32, fn required_float, fn required_array .... +//! Moved out of the parent module by STRA-338: fn validate_owner_index_split, fn validate_owner_metadata_split, fn +//! required_uint, fn required_u32, fn required_float, fn required_array .... #[allow(unused_imports)] use super::*; @@ -84,129 +85,160 @@ pub(super) fn required_array( Ok(values) } +/// The pinned values of the array keys of the model profile. +const PLE_HEAD_OFFSETS: [u64; 16] = [ + 0, + 20_000_003, + 40_000_026, + 60_000_059, + 80_000_106, + 100_000_165, + 120_000_228, + 140_000_297, + 160_000_374, + 180_000_455, + 200_000_548, + 220_000_655, + 240_000_802, + 260_000_955, + 280_001_114, + 300_001_275, +]; +const PLE_HEAD_VOCAB_SIZES: [u64; 16] = [ + 20_000_003, 20_000_023, 20_000_033, 20_000_047, 20_000_059, 20_000_063, 20_000_069, 20_000_077, 20_000_081, + 20_000_093, 20_000_107, 20_000_147, 20_000_153, 20_000_159, 20_000_161, 20_000_171, +]; +const PLE_LAYER_MULTIPLIERS: [u64; 3] = [23_703_573_157_769, 20_109_073_645_365, 8_052_911_324_071]; + +/// The starting value of a topology under construction: every field is replaced by `topology`, in the order of the +/// profile's error precedence, and no blank topology is ever returned. +const BLANK_TOPOLOGY: Qwen4ExpTopology = Qwen4ExpTopology { + architecture: String::new(), + block_count: 0, + embedding_length: 0, + context_length: 0, + compression_ratios: Vec::new(), + full_attention_interval: 0, + expert_count: 0, + expert_used_count: 0, + expert_feed_forward_length: 0, + expert_shared_feed_forward_length: 0, + attention_head_count: 0, + attention_head_count_kv: 0, + attention_key_length: 0, + attention_value_length: 0, + rms_epsilon: 0.0, + hc_count: 0, + hc_low_rank: 0, + rope_dimension_count: 0, + rope_dimension_sections: Vec::new(), + rope_frequency_base: 0.0, + indexer_head_count: 0, + indexer_key_length: 0, + indexer_top_k: 0, + ssm_conv_kernel: 0, + ssm_state_size: 0, + ssm_group_count: 0, + ssm_time_step_rank: 0, + ssm_inner_size: 0, + per_layer_embedding_length: 0, + ple_layers: Vec::new(), + ple_ngram_size: 0, + ple_heads_per_ngram: 0, + ple_conv_kernel: 0, + ple_eos_token_id: 0, + ple_image_token_id: 0, + ple_head_offsets: Vec::new(), + ple_head_vocab_sizes: Vec::new(), + ple_layer_multipliers: Vec::new(), +}; + pub(super) fn topology(metadata: &MetadataSnapshot) -> Result { if metadata.architecture.as_deref() != Some("qwen4exp") { return Err(BindingError::Metadata("general.architecture")); } - let block_count = required_u32(metadata, "qwen4exp.block_count", 48)?; - let embedding_length = required_u32(metadata, "qwen4exp.embedding_length", 2560)?; - let compression_ratios = required_array( - metadata, - "qwen4exp.attention.compress_ratios", - &(0..48).map(|layer| if layer % 4 == 3 { 4 } else { 0 }).collect::>(), - )?; - let full_attention_interval = required_u32(metadata, "qwen4exp.full_attention_interval", 4)?; - let expert_count = required_u32(metadata, "qwen4exp.expert_count", 512)?; - let expert_used_count = required_u32(metadata, "qwen4exp.expert_used_count", 10)?; - let expert_feed_forward_length = required_u32(metadata, "qwen4exp.expert_feed_forward_length", 640)?; - let expert_shared_feed_forward_length = required_u32(metadata, "qwen4exp.expert_shared_feed_forward_length", 640)?; - let attention_head_count = required_u32(metadata, "qwen4exp.attention.head_count", 24)?; - let attention_head_count_kv = required_u32(metadata, "qwen4exp.attention.head_count_kv", 2)?; - let attention_key_length = required_u32(metadata, "qwen4exp.attention.key_length", 256)?; - let attention_value_length = required_u32(metadata, "qwen4exp.attention.value_length", 256)?; - let rms_epsilon = required_float(metadata, "qwen4exp.attention.layer_norm_rms_epsilon")?; - if (rms_epsilon - 1.0e-6).abs() > 1.0e-12 { + let mut t = BLANK_TOPOLOGY; + t.architecture = "qwen4exp".to_owned(); + read_shape(&mut t, metadata)?; + read_experts(&mut t, metadata)?; + read_attention(&mut t, metadata)?; + read_rope(&mut t, metadata)?; + read_indexer(&mut t, metadata)?; + read_ssm(&mut t, metadata)?; + read_ple(&mut t, metadata)?; + t.context_length = required_u32(metadata, "qwen4exp.context_length", 262_144)?; + Ok(t) +} + +fn read_shape(t: &mut Qwen4ExpTopology, metadata: &MetadataSnapshot) -> Result<(), BindingError> { + t.block_count = required_u32(metadata, "qwen4exp.block_count", 48)?; + t.embedding_length = required_u32(metadata, "qwen4exp.embedding_length", 2560)?; + let pattern = (0..48).map(|layer| if layer % 4 == 3 { 4 } else { 0 }).collect::>(); + t.compression_ratios = required_array(metadata, "qwen4exp.attention.compress_ratios", &pattern)?; + t.full_attention_interval = required_u32(metadata, "qwen4exp.full_attention_interval", 4)?; + Ok(()) +} + +fn read_experts(t: &mut Qwen4ExpTopology, metadata: &MetadataSnapshot) -> Result<(), BindingError> { + t.expert_count = required_u32(metadata, "qwen4exp.expert_count", 512)?; + t.expert_used_count = required_u32(metadata, "qwen4exp.expert_used_count", 10)?; + t.expert_feed_forward_length = required_u32(metadata, "qwen4exp.expert_feed_forward_length", 640)?; + t.expert_shared_feed_forward_length = required_u32(metadata, "qwen4exp.expert_shared_feed_forward_length", 640)?; + Ok(()) +} + +fn read_attention(t: &mut Qwen4ExpTopology, metadata: &MetadataSnapshot) -> Result<(), BindingError> { + t.attention_head_count = required_u32(metadata, "qwen4exp.attention.head_count", 24)?; + t.attention_head_count_kv = required_u32(metadata, "qwen4exp.attention.head_count_kv", 2)?; + t.attention_key_length = required_u32(metadata, "qwen4exp.attention.key_length", 256)?; + t.attention_value_length = required_u32(metadata, "qwen4exp.attention.value_length", 256)?; + t.rms_epsilon = required_float(metadata, "qwen4exp.attention.layer_norm_rms_epsilon")?; + if (t.rms_epsilon - 1.0e-6).abs() > 1.0e-12 { return Err(BindingError::Metadata("qwen4exp.attention.layer_norm_rms_epsilon")); } - let hc_count = required_u32(metadata, "qwen4exp.hyper_connection.count", 4)?; - let hc_low_rank = required_u32(metadata, "qwen4exp.hyper_connection.low_rank", 320)?; - let rope_dimension_count = required_u32(metadata, "qwen4exp.rope.dimension_count", 64)?; - let rope_dimension_sections = required_array(metadata, "qwen4exp.rope.dimension_sections", &[11, 11, 10, 0])?; - let rope_frequency_base = required_float(metadata, "qwen4exp.rope.freq_base")?; - if rope_frequency_base != 10_000_000.0 { + Ok(()) +} + +fn read_rope(t: &mut Qwen4ExpTopology, metadata: &MetadataSnapshot) -> Result<(), BindingError> { + t.hc_count = required_u32(metadata, "qwen4exp.hyper_connection.count", 4)?; + t.hc_low_rank = required_u32(metadata, "qwen4exp.hyper_connection.low_rank", 320)?; + t.rope_dimension_count = required_u32(metadata, "qwen4exp.rope.dimension_count", 64)?; + t.rope_dimension_sections = required_array(metadata, "qwen4exp.rope.dimension_sections", &[11, 11, 10, 0])?; + t.rope_frequency_base = required_float(metadata, "qwen4exp.rope.freq_base")?; + if t.rope_frequency_base != 10_000_000.0 { return Err(BindingError::Metadata("qwen4exp.rope.freq_base")); } - let indexer_head_count = required_u32(metadata, "qwen4exp.attention.indexer.head_count", 4)?; - let indexer_key_length = required_u32(metadata, "qwen4exp.attention.indexer.key_length", 128)?; - let indexer_top_k = required_u32(metadata, "qwen4exp.attention.indexer.top_k", 2048)?; - let ssm_conv_kernel = required_u32(metadata, "qwen4exp.ssm.conv_kernel", 4)?; - let ssm_state_size = required_u32(metadata, "qwen4exp.ssm.state_size", 128)?; - let ssm_group_count = required_u32(metadata, "qwen4exp.ssm.group_count", 16)?; - let ssm_time_step_rank = required_u32(metadata, "qwen4exp.ssm.time_step_rank", 48)?; - let ssm_inner_size = required_u32(metadata, "qwen4exp.ssm.inner_size", 6144)?; - let per_layer_embedding_length = required_u32(metadata, "qwen4exp.embedding_length_per_layer_input", 160)?; - let ple_layers = required_array(metadata, "qwen4exp.ple.layers", &[1])?; - let ple_ngram_size = required_u32(metadata, "qwen4exp.ple.ngram_size", 3)?; - let ple_heads_per_ngram = required_u32(metadata, "qwen4exp.ple.heads_per_ngram", 8)?; - let ple_conv_kernel = required_u32(metadata, "qwen4exp.ple.conv_kernel", 4)?; - let ple_eos_token_id = required_u32(metadata, "qwen4exp.ple.eos_token_id", 248_044)?; - let ple_image_token_id = required_u32(metadata, "qwen4exp.ple.image_token_id", 248_056)?; - let ple_head_offsets = required_array( - metadata, - "qwen4exp.ple.head_offsets", - &[ - 0, - 20_000_003, - 40_000_026, - 60_000_059, - 80_000_106, - 100_000_165, - 120_000_228, - 140_000_297, - 160_000_374, - 180_000_455, - 200_000_548, - 220_000_655, - 240_000_802, - 260_000_955, - 280_001_114, - 300_001_275, - ], - )?; - let ple_head_vocab_sizes = required_array( - metadata, - "qwen4exp.ple.head_vocab_sizes", - &[ - 20_000_003, 20_000_023, 20_000_033, 20_000_047, 20_000_059, 20_000_063, 20_000_069, 20_000_077, 20_000_081, - 20_000_093, 20_000_107, 20_000_147, 20_000_153, 20_000_159, 20_000_161, 20_000_171, - ], - )?; - let ple_layer_multipliers = required_array( - metadata, - "qwen4exp.ple.layer_multipliers", - &[23_703_573_157_769, 20_109_073_645_365, 8_052_911_324_071], - )?; - let context_length = required_u32(metadata, "qwen4exp.context_length", 262_144)?; - Ok(Qwen4ExpTopology { - architecture: "qwen4exp".to_owned(), - block_count, - embedding_length, - context_length, - compression_ratios, - full_attention_interval, - expert_count, - expert_used_count, - expert_feed_forward_length, - expert_shared_feed_forward_length, - attention_head_count, - attention_head_count_kv, - attention_key_length, - attention_value_length, - rms_epsilon, - hc_count, - hc_low_rank, - rope_dimension_count, - rope_dimension_sections, - rope_frequency_base, - indexer_head_count, - indexer_key_length, - indexer_top_k, - ssm_conv_kernel, - ssm_state_size, - ssm_group_count, - ssm_time_step_rank, - ssm_inner_size, - per_layer_embedding_length, - ple_layers, - ple_ngram_size, - ple_heads_per_ngram, - ple_conv_kernel, - ple_eos_token_id, - ple_image_token_id, - ple_head_offsets, - ple_head_vocab_sizes, - ple_layer_multipliers, - }) + Ok(()) +} + +fn read_indexer(t: &mut Qwen4ExpTopology, metadata: &MetadataSnapshot) -> Result<(), BindingError> { + t.indexer_head_count = required_u32(metadata, "qwen4exp.attention.indexer.head_count", 4)?; + t.indexer_key_length = required_u32(metadata, "qwen4exp.attention.indexer.key_length", 128)?; + t.indexer_top_k = required_u32(metadata, "qwen4exp.attention.indexer.top_k", 2048)?; + Ok(()) +} + +fn read_ssm(t: &mut Qwen4ExpTopology, metadata: &MetadataSnapshot) -> Result<(), BindingError> { + t.ssm_conv_kernel = required_u32(metadata, "qwen4exp.ssm.conv_kernel", 4)?; + t.ssm_state_size = required_u32(metadata, "qwen4exp.ssm.state_size", 128)?; + t.ssm_group_count = required_u32(metadata, "qwen4exp.ssm.group_count", 16)?; + t.ssm_time_step_rank = required_u32(metadata, "qwen4exp.ssm.time_step_rank", 48)?; + t.ssm_inner_size = required_u32(metadata, "qwen4exp.ssm.inner_size", 6144)?; + t.per_layer_embedding_length = required_u32(metadata, "qwen4exp.embedding_length_per_layer_input", 160)?; + Ok(()) +} + +fn read_ple(t: &mut Qwen4ExpTopology, metadata: &MetadataSnapshot) -> Result<(), BindingError> { + t.ple_layers = required_array(metadata, "qwen4exp.ple.layers", &[1])?; + t.ple_ngram_size = required_u32(metadata, "qwen4exp.ple.ngram_size", 3)?; + t.ple_heads_per_ngram = required_u32(metadata, "qwen4exp.ple.heads_per_ngram", 8)?; + t.ple_conv_kernel = required_u32(metadata, "qwen4exp.ple.conv_kernel", 4)?; + t.ple_eos_token_id = required_u32(metadata, "qwen4exp.ple.eos_token_id", 248_044)?; + t.ple_image_token_id = required_u32(metadata, "qwen4exp.ple.image_token_id", 248_056)?; + t.ple_head_offsets = required_array(metadata, "qwen4exp.ple.head_offsets", &PLE_HEAD_OFFSETS)?; + t.ple_head_vocab_sizes = required_array(metadata, "qwen4exp.ple.head_vocab_sizes", &PLE_HEAD_VOCAB_SIZES)?; + t.ple_layer_multipliers = required_array(metadata, "qwen4exp.ple.layer_multipliers", &PLE_LAYER_MULTIPLIERS)?; + Ok(()) } pub(super) fn validate_tokenizer(tokenizer: &TokenizerMetadata) -> Result<(), BindingError> { diff --git a/crates/model-format/src/qwen4exp/validate_role_inventory.rs b/crates/model-format/src/qwen4exp/validate_role_inventory.rs index 4193483b..1fcd2fac 100644 --- a/crates/model-format/src/qwen4exp/validate_role_inventory.rs +++ b/crates/model-format/src/qwen4exp/validate_role_inventory.rs @@ -3,6 +3,11 @@ #[allow(unused_imports)] use super::*; +/// The GGUF tensor kinds the model profile admits. +const ALLOWED_KINDS: [u32; 13] = [0, 1, 8, 12, 13, 14, 18, 20, 21, 22, 23, 30, 42]; + +type IndexedTensors<'a> = BTreeMap<&'a str, (u8, usize, &'a gguf::TensorInfo)>; + pub(super) fn validate_role_inventory( shards: &[LogicalShardView<'_>; 2], ) -> Result, BindingError> { @@ -10,11 +15,27 @@ pub(super) fn validate_role_inventory( if expected.len() != 1224 { return Err(BindingError::Role("registry_count")); } - let by_name = expected.iter().map(|item| (item.name.as_str(), item)).collect::>(); - let allowed_kinds: BTreeSet = [0, 1, 8, 12, 13, 14, 18, 20, 21, 22, 23, 30, 42].into_iter().collect(); - let mut actual = BTreeMap::new(); + let actual = index_actual(shards)?; let mut roles = BTreeMap::new(); let mut spans: [Vec<(u64, u64)>; 2] = [Vec::new(), Vec::new()]; + for spec in &expected { + let (resolved, span) = resolve_tensor(shards, &actual, spec)?; + spans[resolved.shard as usize].push(span); + if roles.insert(spec.role, resolved).is_some() { + return Err(BindingError::Role("duplicate_role")); + } + } + let by_name = expected.iter().map(|item| item.name.as_str()).collect::>(); + if actual.keys().any(|name| !by_name.contains(name)) || roles.len() != expected.len() { + return Err(BindingError::Role("missing_name")); + } + check_no_overlap(&mut spans)?; + Ok(roles) +} + +/// Every indexed tensor by name: (shard, tensor number, tensor); a name in two places is refused. +fn index_actual<'a>(shards: &'a [LogicalShardView<'_>; 2]) -> Result, BindingError> { + let mut actual = BTreeMap::new(); for (shard_number, shard) in shards.iter().enumerate() { for (tensor_number, tensor) in shard.index.tensors.iter().enumerate() { if actual.insert(tensor.name.as_str(), (shard_number as u8, tensor_number, tensor)).is_some() { @@ -22,82 +43,55 @@ pub(super) fn validate_role_inventory( } } } - for spec in &expected { - let (shard_number, tensor_number, tensor) = - actual.get(spec.name.as_str()).ok_or(BindingError::Role("missing_name"))?; - if spec.shard != *shard_number { - return Err(BindingError::Role("wrong_shard")); - } - if tensor.dimensions != spec.dimensions { - return Err(BindingError::Geometry("dimensions")); - } - if !allowed_kinds.contains(&tensor.kind) || spec.kind.is_some_and(|kind| kind != tensor.kind) { - return Err(BindingError::Geometry("kind")); - } - let (block_elements, block_bytes) = gguf::block_geometry(tensor.kind).ok_or(BindingError::Geometry("kind"))?; - if tensor.dimensions.first().copied().unwrap_or(0) == 0 || tensor.dimensions[0] % block_elements != 0 { - return Err(BindingError::Geometry("block_alignment")); - } - let elements = tensor - .dimensions - .iter() - .try_fold(1u64, |value, dim| value.checked_mul(*dim)) - .ok_or(BindingError::Geometry("element_count"))?; - let bytes = elements - .checked_div(block_elements) - .and_then(|blocks| blocks.checked_mul(block_bytes)) - .ok_or(BindingError::Geometry("byte_count"))?; - if tensor.bytes == 0 || tensor.bytes != bytes { - return Err(BindingError::Geometry("indexed_byte_count")); - } - let shard = &shards[*shard_number as usize]; - let absolute_start = - shard.index.summary.data_start.checked_add(tensor.offset).ok_or(BindingError::Range("absolute_start"))?; - if absolute_start < shard.index.summary.data_start { - return Err(BindingError::Range("data_bounds")); - } - let absolute_end = absolute_start.checked_add(tensor.bytes).ok_or(BindingError::Range("absolute_end"))?; - if absolute_end > shard.index.summary.file_size { - return Err(BindingError::Range("file_bounds")); - } - spans[*shard_number as usize].push((absolute_start, absolute_end)); - let resolved = ResolvedTensor { - shard: *shard_number, - tensor_number: *tensor_number, - name: tensor.name.clone(), - kind: tensor.kind, - dimensions: tensor.dimensions.clone(), - absolute_start, - byte_length: tensor.bytes, - file_size: shard.index.summary.file_size, - }; - if roles.insert(spec.role, resolved).is_some() { - return Err(BindingError::Role("duplicate_role")); - } - } - if actual.keys().any(|name| !by_name.contains_key(name)) || roles.len() != expected.len() { - return Err(BindingError::Role("missing_name")); - } - for span_set in &mut spans { - span_set.sort_unstable(); - if span_set.windows(2).any(|pair| pair[0].1 > pair[1].0) { - return Err(BindingError::Range("overlapping_tensors")); - } - } - Ok(roles) + Ok(actual) } -pub(super) fn plan_row(tensor: &ResolvedTensor, row: u64, expert: Option) -> Result<(u64, u64), BindingError> { - let dimensions = &tensor.dimensions; - match (dimensions.len(), expert) { - (1, None) if matches!(tensor.kind, 0 | 1 | 30) => {} - (1, None) => return Err(BindingError::Geometry("kind")), - (2, None) | (3, Some(_)) => {} - (1 | 2, Some(_)) | (3, None) => return Err(BindingError::Role("rank_mismatch")), - _ => return Err(BindingError::Role("rank")), +/// The indexed tensor of one registry entry, checked against it: shard, dimensions, kind, byte count and file range. +/// Returns it resolved, with its absolute byte span. +fn resolve_tensor( + shards: &[LogicalShardView<'_>; 2], + actual: &IndexedTensors<'_>, + spec: &ExpectedTensor, +) -> Result<(ResolvedTensor, (u64, u64)), BindingError> { + let (shard_number, tensor_number, tensor) = + actual.get(spec.name.as_str()).ok_or(BindingError::Role("missing_name"))?; + if spec.shard != *shard_number { + return Err(BindingError::Role("wrong_shard")); } - let (block_elements, block_bytes) = gguf::block_geometry(tensor.kind).ok_or(BindingError::Geometry("kind"))?; - let dim0 = *dimensions.first().ok_or(BindingError::Geometry("rank"))?; + check_tensor_geometry(spec, tensor)?; + let shard = &shards[*shard_number as usize]; + let span = check_tensor_range(shard, tensor)?; + let resolved = ResolvedTensor { + shard: *shard_number, + tensor_number: *tensor_number, + name: tensor.name.clone(), + kind: tensor.kind, + dimensions: tensor.dimensions.clone(), + absolute_start: span.0, + byte_length: tensor.bytes, + file_size: shard.index.summary.file_size, + }; + Ok((resolved, span)) +} + +fn check_tensor_geometry(spec: &ExpectedTensor, tensor: &gguf::TensorInfo) -> Result<(), BindingError> { + if tensor.dimensions != spec.dimensions { + return Err(BindingError::Geometry("dimensions")); + } + if !ALLOWED_KINDS.contains(&tensor.kind) || spec.kind.is_some_and(|kind| kind != tensor.kind) { + return Err(BindingError::Geometry("kind")); + } + let dim0 = tensor.dimensions.first().copied().unwrap_or(0); + let (_, _, bytes) = geometry_bytes(tensor.kind, &tensor.dimensions, dim0)?; + if tensor.bytes == 0 || tensor.bytes != bytes { + return Err(BindingError::Geometry("indexed_byte_count")); + } + Ok(()) +} + +/// (values per block, bytes per block, bytes of the whole tensor) of a tensor whose first dimension is `dim0`. +fn geometry_bytes(kind: u32, dimensions: &[u64], dim0: u64) -> Result<(u64, u64, u64), BindingError> { + let (block_elements, block_bytes) = gguf::block_geometry(kind).ok_or(BindingError::Geometry("kind"))?; if dim0 == 0 || dim0 % block_elements != 0 { return Err(BindingError::Geometry("block_alignment")); } @@ -105,25 +99,53 @@ pub(super) fn plan_row(tensor: &ResolvedTensor, row: u64, expert: Option) - .iter() .try_fold(1u64, |value, dim| value.checked_mul(*dim)) .ok_or(BindingError::Geometry("element_count"))?; - let indexed_bytes = elements + let bytes = elements .checked_div(block_elements) .and_then(|blocks| blocks.checked_mul(block_bytes)) .ok_or(BindingError::Geometry("byte_count"))?; + Ok((block_elements, block_bytes, bytes)) +} + +/// The absolute byte span of a tensor, inside the data section and the file. +fn check_tensor_range(shard: &LogicalShardView<'_>, tensor: &gguf::TensorInfo) -> Result<(u64, u64), BindingError> { + let absolute_start = + shard.index.summary.data_start.checked_add(tensor.offset).ok_or(BindingError::Range("absolute_start"))?; + if absolute_start < shard.index.summary.data_start { + return Err(BindingError::Range("data_bounds")); + } + let absolute_end = absolute_start.checked_add(tensor.bytes).ok_or(BindingError::Range("absolute_end"))?; + if absolute_end > shard.index.summary.file_size { + return Err(BindingError::Range("file_bounds")); + } + Ok((absolute_start, absolute_end)) +} + +fn check_no_overlap(spans: &mut [Vec<(u64, u64)>; 2]) -> Result<(), BindingError> { + for span_set in spans { + span_set.sort_unstable(); + if span_set.windows(2).any(|pair| pair[0].1 > pair[1].0) { + return Err(BindingError::Range("overlapping_tensors")); + } + } + Ok(()) +} + +pub(super) fn plan_row(tensor: &ResolvedTensor, row: u64, expert: Option) -> Result<(u64, u64), BindingError> { + check_rank(tensor, expert)?; + let dimensions = &tensor.dimensions; + let dim0 = *dimensions.first().ok_or(BindingError::Geometry("rank"))?; + let (block_elements, block_bytes, indexed_bytes) = geometry_bytes(tensor.kind, dimensions, dim0)?; if tensor.byte_length == 0 || indexed_bytes != tensor.byte_length { return Err(BindingError::Geometry("indexed_byte_count")); } let row_bytes = (dim0 / block_elements).checked_mul(block_bytes).ok_or(BindingError::Range("row_bytes"))?; - let relative = match (dimensions.len(), expert) { - (1, None) if row == 0 => Some(0), - (2, None) if row < dimensions[1] => row.checked_mul(row_bytes), - (3, Some(expert)) if expert < dimensions[2] && row < dimensions[1] => expert - .checked_mul(dimensions[1]) - .and_then(|base| base.checked_add(row)) - .and_then(|index| index.checked_mul(row_bytes)), - (1..=3, _) => return Err(BindingError::Range("row_index")), - _ => unreachable!("rank checked above"), - } - .ok_or(BindingError::Range("row_offset"))?; + let relative = relative_offset(dimensions, row, expert, row_bytes)?; + check_row_bounds(tensor, relative, row_bytes)?; + Ok((relative, row_bytes)) +} + +/// The row lies inside the tensor and inside the file. +fn check_row_bounds(tensor: &ResolvedTensor, relative: u64, row_bytes: u64) -> Result<(), BindingError> { if row_bytes == 0 || relative.checked_add(row_bytes).is_none_or(|end| end > tensor.byte_length) { return Err(BindingError::Range("tensor_bounds")); } @@ -135,7 +157,33 @@ pub(super) fn plan_row(tensor: &ResolvedTensor, row: u64, expert: Option) - { return Err(BindingError::Range("file_bounds")); } - Ok((relative, row_bytes)) + Ok(()) +} + +/// The rank of the tensor suits the row addressing: vectors of a plain kind, matrices, or expert stacks with an expert. +fn check_rank(tensor: &ResolvedTensor, expert: Option) -> Result<(), BindingError> { + match (tensor.dimensions.len(), expert) { + (1, None) if matches!(tensor.kind, 0 | 1 | 30) => Ok(()), + (1, None) => Err(BindingError::Geometry("kind")), + (2, None) | (3, Some(_)) => Ok(()), + (1 | 2, Some(_)) | (3, None) => Err(BindingError::Role("rank_mismatch")), + _ => Err(BindingError::Role("rank")), + } +} + +/// Byte offset of a row (of an expert) inside the tensor. +fn relative_offset(dimensions: &[u64], row: u64, expert: Option, row_bytes: u64) -> Result { + match (dimensions.len(), expert) { + (1, None) if row == 0 => Some(0), + (2, None) if row < dimensions[1] => row.checked_mul(row_bytes), + (3, Some(expert)) if expert < dimensions[2] && row < dimensions[1] => expert + .checked_mul(dimensions[1]) + .and_then(|base| base.checked_add(row)) + .and_then(|index| index.checked_mul(row_bytes)), + (1..=3, _) => return Err(BindingError::Range("row_index")), + _ => unreachable!("rank checked above"), + } + .ok_or(BindingError::Range("row_offset")) } /// Plan an exact finite row tile using the existing single-row geometry diff --git a/crates/model-format/src/qwen4exp/whole_moe_matrix_sdet.rs b/crates/model-format/src/qwen4exp/whole_moe_matrix_sdet.rs index f0c3fe68..3dc0955c 100644 --- a/crates/model-format/src/qwen4exp/whole_moe_matrix_sdet.rs +++ b/crates/model-format/src/qwen4exp/whole_moe_matrix_sdet.rs @@ -2,103 +2,137 @@ use super::*; +/// Independent layout literals from upstream gguf_reader.hpp: +/// GU has ten 256-element blocks; Down has twenty 32-element +/// blocks or ten 64-element blocks. These are logical planner +/// descriptors, never admitted artifact identities or file fixtures. +/// kind, routed, Down, encoded row bytes, 64-row bytes, matrix bytes. +const LAYOUTS: [(u32, bool, bool, u64, u64, u64); 12] = [ + (18, true, false, 980, 62_720, 627_200), + (21, true, false, 1100, 70_400, 704_000), + (22, true, false, 820, 52_480, 524_800), + (23, true, false, 1360, 87_040, 870_400), + (20, true, true, 360, 23_040, 921_600), + (42, true, true, 180, 11_520, 460_800), + (12, false, false, 1440, 92_160, 921_600), + (13, false, false, 1760, 112_640, 1_126_400), + (14, false, false, 2100, 134_400, 1_344_000), + (23, false, false, 1360, 87_040, 870_400), + (20, false, true, 360, 23_040, 921_600), + (8, false, true, 680, 43_520, 1_740_800), +]; + +/// What the planner must produce for one layout: bytes per encoded row, per 64-row tile and per matrix, and the rows. +struct Expected { + stride: u64, + tile_bytes: u64, + matrix_bytes: u64, + rows: u64, +} + #[test] fn complete_moe_spans_match_literal_legacy_tiles_and_refuse_boundary_crossing() { - // Independent layout literals from upstream gguf_reader.hpp: - // GU has ten 256-element blocks; Down has twenty 32-element - // blocks or ten 64-element blocks. These are logical planner - // descriptors, never admitted artifact identities or file fixtures. - // kind, routed, Down, encoded row bytes, 64-row bytes, matrix bytes. - let layouts = [ - (18, true, false, 980, 62_720, 627_200), - (21, true, false, 1100, 70_400, 704_000), - (22, true, false, 820, 52_480, 524_800), - (23, true, false, 1360, 87_040, 870_400), - (20, true, true, 360, 23_040, 921_600), - (42, true, true, 180, 11_520, 460_800), - (12, false, false, 1440, 92_160, 921_600), - (13, false, false, 1760, 112_640, 1_126_400), - (14, false, false, 2100, 134_400, 1_344_000), - (23, false, false, 1360, 87_040, 870_400), - (20, false, true, 360, 23_040, 921_600), - (8, false, true, 680, 43_520, 1_740_800), - ]; - for (kind, routed, down, stride, tile_bytes, matrix_bytes) in layouts { - let (columns, rows) = if down { (640, 2560) } else { (2560, 640) }; - let dimensions = if routed { vec![columns, rows, 512] } else { vec![columns, rows] }; - let byte_length = matrix_bytes * if routed { 512 } else { 1 }; - let tensor = ResolvedTensor { - shard: 0, - tensor_number: 0, - name: "independent.logical.moe.span".to_owned(), - kind, - dimensions, - absolute_start: 4096, - byte_length, - file_size: 4096 + byte_length, - }; - let roles: &[LayerRole] = match (routed, down) { - (true, false) => &[LayerRole::FfnGateExperts, LayerRole::FfnUpExperts], - (true, true) => &[LayerRole::FfnDownExperts], - (false, false) => &[LayerRole::FfnGateShared, LayerRole::FfnUpShared], - (false, true) => &[LayerRole::FfnDownShared], - }; - let experts: &[Option] = if routed { &[Some(0), Some(1), Some(511)] } else { &[None] }; - for &layer_role in roles { - let role = TensorRole::Layer { layer: 47, role: layer_role }; - for &expert in experts { - let base = expert.unwrap_or(0) * matrix_bytes; - assert_eq!(plan_stream_rows(&tensor, role, 0, rows, expert).unwrap(), (base, matrix_bytes)); - // The literal legacy offsets cover every byte once, in order, - // with no expert transition, tail, padding or hidden gap. - for tile in 0..rows / 64 { - let expected = (base + tile * tile_bytes, tile_bytes); - assert_eq!(plan_rows(&tensor, tile * 64, 64, expert).unwrap(), expected); - assert_eq!(plan_stream_rows(&tensor, role, tile * 64, 64, expert).unwrap(), expected); - } - assert_eq!(plan_row(&tensor, rows - 1, expert).unwrap(), (base + matrix_bytes - stride, stride)); - for (first, count) in [ - (0, 0), - (0, 65), - (0, rows - 1), - (0, rows + 1), - (1, rows), - (rows - 63, 64), - (rows, 1), - (u64::MAX, 64), - (1, u64::MAX), - ] { - assert!(plan_stream_rows(&tensor, role, first, count, expert).is_err()); - } - let other_role = TensorRole::Layer { layer: 47, role: LayerRole::HcFfnNorm }; - assert!(plan_stream_rows(&tensor, other_role, 0, rows, expert).is_err()); - assert!(plan_rows(&tensor, 0, rows, expert).is_err()); + for layout in LAYOUTS { + check_layout(layout); + } +} - let mut malformed = tensor.clone(); - malformed.dimensions[0] += 1; - assert!(plan_stream_rows(&malformed, role, 0, rows, expert).is_err()); - malformed = tensor.clone(); - malformed.dimensions[1] -= 1; - assert!(plan_stream_rows(&malformed, role, 0, rows, expert).is_err()); - malformed = tensor.clone(); - malformed.byte_length -= 1; - assert!(plan_stream_rows(&malformed, role, 0, rows, expert).is_err()); - malformed = tensor.clone(); - malformed.file_size = 4096 + base + matrix_bytes - 1; - assert!(plan_stream_rows(&malformed, role, 0, rows, expert).is_err()); - malformed = tensor.clone(); - malformed.absolute_start = u64::MAX - matrix_bytes + 1; - malformed.file_size = u64::MAX; - assert!(plan_stream_rows(&malformed, role, 0, rows, expert).is_err()); - } - let wrong_selector = if routed { None } else { Some(0) }; - assert!(plan_stream_rows(&tensor, role, 0, rows, wrong_selector).is_err()); - if routed { - assert!(plan_stream_rows(&tensor, role, 0, rows, Some(512)).is_err()); - let mut malformed = tensor.clone(); - malformed.dimensions[2] = 511; - assert!(plan_stream_rows(&malformed, role, 0, rows, Some(0)).is_err()); - } +fn check_layout((kind, routed, down, stride, tile_bytes, matrix_bytes): (u32, bool, bool, u64, u64, u64)) { + let (columns, rows) = if down { (640, 2560) } else { (2560, 640) }; + let dimensions = if routed { vec![columns, rows, 512] } else { vec![columns, rows] }; + let byte_length = matrix_bytes * if routed { 512 } else { 1 }; + let tensor = ResolvedTensor { + shard: 0, + tensor_number: 0, + name: "independent.logical.moe.span".to_owned(), + kind, + dimensions, + absolute_start: 4096, + byte_length, + file_size: 4096 + byte_length, + }; + let roles: &[LayerRole] = match (routed, down) { + (true, false) => &[LayerRole::FfnGateExperts, LayerRole::FfnUpExperts], + (true, true) => &[LayerRole::FfnDownExperts], + (false, false) => &[LayerRole::FfnGateShared, LayerRole::FfnUpShared], + (false, true) => &[LayerRole::FfnDownShared], + }; + let experts: &[Option] = if routed { &[Some(0), Some(1), Some(511)] } else { &[None] }; + let expected = Expected { stride, tile_bytes, matrix_bytes, rows }; + for &layer_role in roles { + let role = TensorRole::Layer { layer: 47, role: layer_role }; + for &expert in experts { + check_expert(&tensor, role, expert, &expected); } + check_selectors(&tensor, role, routed, rows); + } +} + +fn check_expert(tensor: &ResolvedTensor, role: TensorRole, expert: Option, e: &Expected) { + let (rows, matrix_bytes) = (e.rows, e.matrix_bytes); + let base = expert.unwrap_or(0) * matrix_bytes; + assert_eq!(plan_stream_rows(tensor, role, 0, rows, expert).unwrap(), (base, matrix_bytes)); + // The literal legacy offsets cover every byte once, in order, + // with no expert transition, tail, padding or hidden gap. + for tile in 0..rows / 64 { + let expected = (base + tile * e.tile_bytes, e.tile_bytes); + assert_eq!(plan_rows(tensor, tile * 64, 64, expert).unwrap(), expected); + assert_eq!(plan_stream_rows(tensor, role, tile * 64, 64, expert).unwrap(), expected); + } + assert_eq!(plan_row(tensor, rows - 1, expert).unwrap(), (base + matrix_bytes - e.stride, e.stride)); + for (first, count) in boundary_ranges(rows) { + assert!(plan_stream_rows(tensor, role, first, count, expert).is_err()); + } + let other_role = TensorRole::Layer { layer: 47, role: LayerRole::HcFfnNorm }; + assert!(plan_stream_rows(tensor, other_role, 0, rows, expert).is_err()); + assert!(plan_rows(tensor, 0, rows, expert).is_err()); + check_malformed(tensor, role, expert, e); +} + +/// Ranges that cross a boundary or are empty, oversized, overflowing or not the whole matrix. +fn boundary_ranges(rows: u64) -> [(u64, u64); 9] { + [ + (0, 0), + (0, 65), + (0, rows - 1), + (0, rows + 1), + (1, rows), + (rows - 63, 64), + (rows, 1), + (u64::MAX, 64), + (1, u64::MAX), + ] +} + +fn check_malformed(tensor: &ResolvedTensor, role: TensorRole, expert: Option, e: &Expected) { + let base = expert.unwrap_or(0) * e.matrix_bytes; + let refused = |malformed: &ResolvedTensor| assert!(plan_stream_rows(malformed, role, 0, e.rows, expert).is_err()); + let mut malformed = tensor.clone(); + malformed.dimensions[0] += 1; + refused(&malformed); + malformed = tensor.clone(); + malformed.dimensions[1] -= 1; + refused(&malformed); + malformed = tensor.clone(); + malformed.byte_length -= 1; + refused(&malformed); + malformed = tensor.clone(); + malformed.file_size = 4096 + base + e.matrix_bytes - 1; + refused(&malformed); + malformed = tensor.clone(); + malformed.absolute_start = u64::MAX - e.matrix_bytes + 1; + malformed.file_size = u64::MAX; + refused(&malformed); +} + +/// A routed role needs an expert selector (in range, on a three-dimensional tensor); a shared one refuses it. +fn check_selectors(tensor: &ResolvedTensor, role: TensorRole, routed: bool, rows: u64) { + let wrong_selector = if routed { None } else { Some(0) }; + assert!(plan_stream_rows(tensor, role, 0, rows, wrong_selector).is_err()); + if routed { + assert!(plan_stream_rows(tensor, role, 0, rows, Some(512)).is_err()); + let mut malformed = tensor.clone(); + malformed.dimensions[2] = 511; + assert!(plan_stream_rows(&malformed, role, 0, rows, Some(0)).is_err()); } } diff --git a/crates/model-format/src/qwen4exp_digest_capture/capture_admit.rs b/crates/model-format/src/qwen4exp_digest_capture/capture_admit.rs index 9b3efdc3..f1aef7df 100644 --- a/crates/model-format/src/qwen4exp_digest_capture/capture_admit.rs +++ b/crates/model-format/src/qwen4exp_digest_capture/capture_admit.rs @@ -13,10 +13,8 @@ pub(super) fn capture_admit(capacity: usize, future: usize, available: usize) -> Ok(()) } -pub(super) fn provisional_descriptor( - index: &TensorIndex, - role: TensorRole, -) -> Result { +/// The GGUF name of the routed-expert tensor a role stands for. +fn expert_tensor_name(role: TensorRole) -> Result { let TensorRole::Layer { layer, role: layer_role } = role else { return Err(ResidentExpertSourceError::Geometry); }; @@ -26,7 +24,14 @@ pub(super) fn provisional_descriptor( LayerRole::FfnDownExperts => "ffn_down_exps.weight", _ => return Err(ResidentExpertSourceError::Geometry), }; - let name = format!("blk.{layer}.{suffix}"); + Ok(format!("blk.{layer}.{suffix}")) +} + +pub(super) fn provisional_descriptor( + index: &TensorIndex, + role: TensorRole, +) -> Result { + let name = expert_tensor_name(role)?; let (tensor_number, tensor) = index .tensors .iter() diff --git a/crates/model-format/src/qwen4exp_digest_capture/impl_provisionalexpertsource.rs b/crates/model-format/src/qwen4exp_digest_capture/impl_provisionalexpertsource.rs index 9c4ba92e..cdbb4ea2 100644 --- a/crates/model-format/src/qwen4exp_digest_capture/impl_provisionalexpertsource.rs +++ b/crates/model-format/src/qwen4exp_digest_capture/impl_provisionalexpertsource.rs @@ -42,17 +42,56 @@ impl ProvisionalExpertSource { index: &TensorIndex, retained_kar: Option<&File>, ) -> Result<(), ResidentExpertSourceError> { - // Observation ONLY: seals/SHA/CRC stay at the original later KAR gate. - // The keeper's already retained memfd pages are in MemAvailable, so its - // 55 GiB is not also charged as a future allocation. - let observed_kar = retained_kar - .and_then(|file| file.metadata().ok()) - .filter(|metadata| metadata.is_file() && metadata.len() == RETAINED_KAR_BYTES) - .ok_or(ResidentExpertSourceError::MemoryAdmission)?; - let _ = observed_kar; + check_retained_kar(retained_kar)?; if index.summary.file_size != PINNED_IDENTITIES[0].0 || index.tensors.len() != 1223 { return Err(ResidentExpertSourceError::Geometry); } + self.reserve_tables()?; + // First geometry pass prevents allocation before complete closed layout. + self.plan_and_admit(index)?; + self.capture_cells(index) + } + + /// Allocates the cell of every expert tensor under the memory admission, then admits the finished capture. + fn capture_cells(&mut self, index: &TensorIndex) -> Result<(), ResidentExpertSourceError> { + let mut remaining = self.source_bytes; + for role in expert_roles() { + let descriptor = provisional_descriptor(index, role)?; + self.check_disjoint(&descriptor)?; + remaining = self.allocate_cell(descriptor, remaining)?; + } + capture_admit(0, FUTURE_OWNERS, memory_available()?) + } + + /// The geometry pass over every expert tensor, then the admission of the whole plan against the memory observed. + pub(super) fn plan_and_admit(&mut self, index: &TensorIndex) -> Result<(), ResidentExpertSourceError> { + self.add_source_bytes(index)?; + let planned = self.charged.checked_add(self.source_bytes).ok_or(ResidentExpertSourceError::MemoryAdmission)?; + self.observed = memory_available()?; + capture_admit(planned, FUTURE_OWNERS, self.observed) + } + + /// First geometry pass: the bytes of every expert tensor, summed into `source_bytes`. + pub(super) fn add_source_bytes(&mut self, index: &TensorIndex) -> Result<(), ResidentExpertSourceError> { + for role in expert_roles() { + let descriptor = provisional_descriptor(index, role)?; + self.source_bytes = + self.source_bytes.checked_add(descriptor.bytes).ok_or(ResidentExpertSourceError::Geometry)?; + } + Ok(()) + } + + /// Adds an allocation to the charged total, which must stay within the source cap. + pub(super) fn charge(&mut self, charged_bytes: usize) -> Result<(), ResidentExpertSourceError> { + self.charged = self.charged.checked_add(charged_bytes).ok_or(ResidentExpertSourceError::MemoryAdmission)?; + if self.charged as u64 > SOURCE_CAP { + return Err(ResidentExpertSourceError::MemoryAdmission); + } + Ok(()) + } + + /// Room for the cell and bank tables, charged with the size of the capture itself. + fn reserve_tables(&mut self) -> Result<(), ResidentExpertSourceError> { self.cells.try_reserve_exact(BANKS).map_err(|_| ResidentExpertSourceError::Allocation)?; self.banks.try_reserve_exact(BANKS).map_err(|_| ResidentExpertSourceError::Allocation)?; self.charged = self @@ -62,83 +101,80 @@ impl ProvisionalExpertSource { .and_then(|n| n.checked_add(self.banks.capacity().checked_mul(size_of::())?)) .and_then(|n| n.checked_add(size_of::() + size_of::())) .ok_or(ResidentExpertSourceError::MemoryAdmission)?; - // First geometry pass prevents allocation before complete closed layout. - for layer in 0..48 { - for role in [LayerRole::FfnGateExperts, LayerRole::FfnUpExperts, LayerRole::FfnDownExperts] { - let descriptor = provisional_descriptor(index, TensorRole::Layer { layer, role })?; - self.source_bytes = - self.source_bytes.checked_add(descriptor.bytes).ok_or(ResidentExpertSourceError::Geometry)?; - } - } - let planned = self.charged.checked_add(self.source_bytes).ok_or(ResidentExpertSourceError::MemoryAdmission)?; - self.observed = memory_available()?; - capture_admit(planned, FUTURE_OWNERS, self.observed)?; - let mut remaining = self.source_bytes; - for layer in 0..48 { - for role in [LayerRole::FfnGateExperts, LayerRole::FfnUpExperts, LayerRole::FfnDownExperts] { - let descriptor = provisional_descriptor(index, TensorRole::Layer { layer, role })?; - for previous in &self.cells { - let left = previous.descriptor.absolute_start; - let right = left + previous.descriptor.bytes as u64; - let start = descriptor.absolute_start; - let end = start + descriptor.bytes as u64; - if left < end && start < right { - return Err(ResidentExpertSourceError::Geometry); - } - } - capture_admit(remaining, FUTURE_OWNERS, memory_available()?)?; - let mut bytes = Vec::new(); - bytes.try_reserve_exact(descriptor.bytes).map_err(|_| ResidentExpertSourceError::Allocation)?; - let charged_bytes = bytes.capacity(); - self.charged = - self.charged.checked_add(charged_bytes).ok_or(ResidentExpertSourceError::MemoryAdmission)?; - if self.charged as u64 > SOURCE_CAP { - return Err(ResidentExpertSourceError::MemoryAdmission); - } - capture_admit( - remaining - .checked_sub(descriptor.bytes) - .and_then(|n| n.checked_add(charged_bytes)) - .ok_or(ResidentExpertSourceError::MemoryAdmission)?, - FUTURE_OWNERS, - memory_available()?, - )?; - bytes.resize(descriptor.bytes, 0); - self.cells.push(CapturedTensor { - descriptor, - bytes: bytes.into_boxed_slice(), - charged_bytes, - covered: 0, - }); - remaining -= descriptor.bytes; - } - } - capture_admit(0, FUTURE_OWNERS, memory_available()?)?; Ok(()) } - pub(crate) fn observe(&mut self, position: u64, chunk: &[u8]) { - if let Some(incremental) = &mut self.incremental { - #[cfg(test)] - let available = incremental.test_available; - let result = incremental.observe_inner(position, chunk, || { - #[cfg(test)] - if let Some(available) = available { - return Ok(available); - } - memory_available() - }); - if let Err(error) = result { - self.fail(error); + + /// The descriptor's file range overlaps none of the cells captured so far. + fn check_disjoint(&self, descriptor: &BankDescriptor) -> Result<(), ResidentExpertSourceError> { + for previous in &self.cells { + let left = previous.descriptor.absolute_start; + let right = left + previous.descriptor.bytes as u64; + let start = descriptor.absolute_start; + let end = start + descriptor.bytes as u64; + if left < end && start < right { + return Err(ResidentExpertSourceError::Geometry); } + } + Ok(()) + } + + /// Admits, allocates and charges the cell of one tensor; returns the bytes still to allocate after it. + fn allocate_cell( + &mut self, + descriptor: BankDescriptor, + remaining: usize, + ) -> Result { + capture_admit(remaining, FUTURE_OWNERS, memory_available()?)?; + let mut bytes = Vec::new(); + bytes.try_reserve_exact(descriptor.bytes).map_err(|_| ResidentExpertSourceError::Allocation)?; + let charged_bytes = bytes.capacity(); + self.charge(charged_bytes)?; + capture_admit( + remaining + .checked_sub(descriptor.bytes) + .and_then(|n| n.checked_add(charged_bytes)) + .ok_or(ResidentExpertSourceError::MemoryAdmission)?, + FUTURE_OWNERS, + memory_available()?, + )?; + bytes.resize(descriptor.bytes, 0); + self.cells.push(CapturedTensor { descriptor, bytes: bytes.into_boxed_slice(), charged_bytes, covered: 0 }); + Ok(remaining - descriptor.bytes) + } + pub(crate) fn observe(&mut self, position: u64, chunk: &[u8]) { + if self.incremental.is_some() { + self.observe_incremental(position, chunk); return; } if self.error.is_some() { return; } - let Some(end) = position.checked_add(chunk.len() as u64) else { - self.fail(ResidentExpertSourceError::Geometry); + if let Err(error) = self.copy_chunk(position, chunk) { + self.fail(error); + } + } + + fn observe_incremental(&mut self, position: u64, chunk: &[u8]) { + let Some(incremental) = &mut self.incremental else { return; }; + #[cfg(test)] + let available = incremental.test_available; + let result = incremental.observe_inner(position, chunk, || { + #[cfg(test)] + if let Some(available) = available { + return Ok(available); + } + memory_available() + }); + if let Err(error) = result { + self.fail(error); + } + } + + /// Copies the part of the chunk that lies inside each cell; the cells must fill up in file order. + fn copy_chunk(&mut self, position: u64, chunk: &[u8]) -> Result<(), ResidentExpertSourceError> { + let end = position.checked_add(chunk.len() as u64).ok_or(ResidentExpertSourceError::Geometry)?; for cell in &mut self.cells { let start = cell.descriptor.absolute_start; let bank_end = start + cell.descriptor.bytes as u64; @@ -150,13 +186,13 @@ impl ProvisionalExpertSource { let offset = (left - start) as usize; let count = (right - left) as usize; if offset != cell.covered { - self.fail(ResidentExpertSourceError::Geometry); - return; + return Err(ResidentExpertSourceError::Geometry); } let source = (left - position) as usize; cell.bytes[offset..offset + count].copy_from_slice(&chunk[source..source + count]); cell.covered += count; } + Ok(()) } pub(crate) fn bind_verified(&mut self, source: &mut VerifiedGgufFile) { if self.error.is_none() @@ -184,3 +220,14 @@ impl ProvisionalExpertSource { } } } + +/// Observation ONLY: seals/SHA/CRC stay at the original later KAR gate. +/// The keeper's already retained memfd pages are in MemAvailable, so its +/// 55 GiB is not also charged as a future allocation. +pub(super) fn check_retained_kar(retained_kar: Option<&File>) -> Result<(), ResidentExpertSourceError> { + retained_kar + .and_then(|file| file.metadata().ok()) + .filter(|metadata| metadata.is_file() && metadata.len() == RETAINED_KAR_BYTES) + .map(|_| ()) + .ok_or(ResidentExpertSourceError::MemoryAdmission) +} diff --git a/crates/model-format/src/qwen4exp_digest_capture/impl_provisionalexpertsource_2.rs b/crates/model-format/src/qwen4exp_digest_capture/impl_provisionalexpertsource_2.rs index 7e5c9193..84129fe1 100644 --- a/crates/model-format/src/qwen4exp_digest_capture/impl_provisionalexpertsource_2.rs +++ b/crates/model-format/src/qwen4exp_digest_capture/impl_provisionalexpertsource_2.rs @@ -16,17 +16,29 @@ impl ProvisionalExpertSource { index: &TensorIndex, retained_kar: Option<&File>, ) -> Result<(), ResidentExpertSourceError> { - // Observation ONLY: seals/SHA/CRC stay at the original later KAR gate. - // The keeper's already retained memfd pages are in MemAvailable, so its - // 55 GiB is not also charged as a future allocation. - let observed_kar = retained_kar - .and_then(|file| file.metadata().ok()) - .filter(|metadata| metadata.is_file() && metadata.len() == RETAINED_KAR_BYTES) - .ok_or(ResidentExpertSourceError::MemoryAdmission)?; - let _ = observed_kar; + check_retained_kar(retained_kar)?; if index.summary.file_size != PINNED_IDENTITIES[0].0 || index.tensors.len() != 1223 { return Err(ResidentExpertSourceError::Geometry); } + self.reserve_incremental_tables()?; + // First geometry pass prevents allocation before complete closed layout. + self.plan_and_admit(index)?; + self.reserve_incremental_cells(index) + } + + /// Reserves the cell of every expert tensor under the memory admission, then admits the finished reservation. + fn reserve_incremental_cells(&mut self, index: &TensorIndex) -> Result<(), ResidentExpertSourceError> { + let mut remaining = self.source_bytes; + for role in expert_roles() { + let descriptor = provisional_descriptor(index, role)?; + self.check_incremental_disjoint(&descriptor)?; + remaining = self.reserve_incremental_cell(descriptor, remaining)?; + } + capture_admit(self.charged, FUTURE_OWNERS, memory_available()?) + } + + /// Room for the cell, bank and incremental tables, charged with the size of the capture itself. + fn reserve_incremental_tables(&mut self) -> Result<(), ResidentExpertSourceError> { self.cells.try_reserve_exact(BANKS).map_err(|_| ResidentExpertSourceError::Allocation)?; self.banks.try_reserve_exact(BANKS).map_err(|_| ResidentExpertSourceError::Allocation)?; let mut incremental_cells = Vec::new(); @@ -46,81 +58,53 @@ impl ProvisionalExpertSource { }) .and_then(|n| n.checked_add(size_of::() + size_of::())) .ok_or(ResidentExpertSourceError::MemoryAdmission)?; - // First geometry pass prevents allocation before complete closed layout. - for layer in 0..48 { - for role in [LayerRole::FfnGateExperts, LayerRole::FfnUpExperts, LayerRole::FfnDownExperts] { - let descriptor = provisional_descriptor(index, TensorRole::Layer { layer, role })?; - self.source_bytes = - self.source_bytes.checked_add(descriptor.bytes).ok_or(ResidentExpertSourceError::Geometry)?; - } - } - let planned = self.charged.checked_add(self.source_bytes).ok_or(ResidentExpertSourceError::MemoryAdmission)?; - self.observed = memory_available()?; - capture_admit(planned, FUTURE_OWNERS, self.observed)?; - let mut remaining = self.source_bytes; - for layer in 0..48 { - for role in [LayerRole::FfnGateExperts, LayerRole::FfnUpExperts, LayerRole::FfnDownExperts] { - let descriptor = provisional_descriptor(index, TensorRole::Layer { layer, role })?; - for previous in &self.incremental.as_ref().ok_or(ResidentExpertSourceError::Geometry)?.cells { - let left = previous.descriptor.absolute_start; - let right = left + previous.descriptor.bytes as u64; - let start = descriptor.absolute_start; - let end = start + descriptor.bytes as u64; - if left < end && start < right { - return Err(ResidentExpertSourceError::Geometry); - } - } - // Reserved but untouched pages remain a full commitment. Unlike the - // original zero-fill, reserve does not make them resident yet. - let committed = - self.charged.checked_add(remaining).ok_or(ResidentExpertSourceError::MemoryAdmission)?; - capture_admit(committed, FUTURE_OWNERS, memory_available()?)?; - let mut bytes = Vec::new(); - bytes.try_reserve_exact(descriptor.bytes).map_err(|_| ResidentExpertSourceError::Allocation)?; - let charged_bytes = bytes.capacity(); - self.charged = - self.charged.checked_add(charged_bytes).ok_or(ResidentExpertSourceError::MemoryAdmission)?; - if self.charged as u64 > SOURCE_CAP { - return Err(ResidentExpertSourceError::MemoryAdmission); - } - capture_admit( - self.charged - .checked_add( - remaining - .checked_sub(descriptor.bytes) - .ok_or(ResidentExpertSourceError::MemoryAdmission)?, - ) - .ok_or(ResidentExpertSourceError::MemoryAdmission)?, - FUTURE_OWNERS, - memory_available()?, - )?; - self.incremental.as_mut().ok_or(ResidentExpertSourceError::Geometry)?.cells.push(IncrementalTensor { - descriptor, - bytes, - charged_bytes, - covered: 0, - }); - remaining -= descriptor.bytes; - } - } - capture_admit(self.charged, FUTURE_OWNERS, memory_available()?)?; Ok(()) } - pub(super) fn finish_incremental(&mut self, source: &VerifiedGgufFile) -> Result<(), ResidentExpertSourceError> { - let incremental = self.incremental.as_ref().ok_or(ResidentExpertSourceError::Geometry)?; - if !self.cells.is_empty() || incremental.cells.len() != BANKS || self.cells.capacity() < incremental.cells.len() - { - return Err(ResidentExpertSourceError::Geometry); - } - for cell in &incremental.cells { - if cell.covered != cell.descriptor.bytes - || cell.bytes.len() != cell.descriptor.bytes - || cell.bytes.capacity() != cell.charged_bytes - || provisional_descriptor(source.index(), cell.descriptor.role)? != cell.descriptor - { + + /// The descriptor's file range overlaps none of the cells reserved so far. + fn check_incremental_disjoint(&self, descriptor: &BankDescriptor) -> Result<(), ResidentExpertSourceError> { + for previous in &self.incremental.as_ref().ok_or(ResidentExpertSourceError::Geometry)?.cells { + let left = previous.descriptor.absolute_start; + let right = left + previous.descriptor.bytes as u64; + let start = descriptor.absolute_start; + let end = start + descriptor.bytes as u64; + if left < end && start < right { return Err(ResidentExpertSourceError::Geometry); } } + Ok(()) + } + + /// Admits, reserves and charges the cell of one tensor; returns the bytes still to reserve after it. + fn reserve_incremental_cell( + &mut self, + descriptor: BankDescriptor, + remaining: usize, + ) -> Result { + // Reserved but untouched pages remain a full commitment. Unlike the + // original zero-fill, reserve does not make them resident yet. + let committed = self.charged.checked_add(remaining).ok_or(ResidentExpertSourceError::MemoryAdmission)?; + capture_admit(committed, FUTURE_OWNERS, memory_available()?)?; + let mut bytes = Vec::new(); + bytes.try_reserve_exact(descriptor.bytes).map_err(|_| ResidentExpertSourceError::Allocation)?; + let charged_bytes = bytes.capacity(); + self.charge(charged_bytes)?; + let rest = self.admit_rest(remaining, descriptor.bytes)?; + let cells = &mut self.incremental.as_mut().ok_or(ResidentExpertSourceError::Geometry)?.cells; + cells.push(IncrementalTensor { descriptor, bytes, charged_bytes, covered: 0 }); + Ok(rest) + } + + /// The bytes left to reserve after `taken`, once the charged total plus them is admitted. + fn admit_rest(&self, remaining: usize, taken: usize) -> Result { + let rest = remaining.checked_sub(taken).ok_or(ResidentExpertSourceError::MemoryAdmission)?; + let total = self.charged.checked_add(rest).ok_or(ResidentExpertSourceError::MemoryAdmission)?; + capture_admit(total, FUTURE_OWNERS, memory_available()?)?; + Ok(rest) + } + + pub(super) fn finish_incremental(&mut self, source: &VerifiedGgufFile) -> Result<(), ResidentExpertSourceError> { + self.check_incremental_complete(source)?; // Original whole SHA/strict index completed before bind calls this. // Move only fully initialized spans into the unchanged opaque gate. let incremental = self.incremental.take().ok_or(ResidentExpertSourceError::Geometry)?; @@ -134,6 +118,31 @@ impl ProvisionalExpertSource { } Ok(()) } + + /// Every incremental cell is fully written, exactly as large as charged, and still the source's descriptor. + fn check_incremental_complete(&self, source: &VerifiedGgufFile) -> Result<(), ResidentExpertSourceError> { + let incremental = self.incremental.as_ref().ok_or(ResidentExpertSourceError::Geometry)?; + if !self.cells.is_empty() || incremental.cells.len() != BANKS || self.cells.capacity() < incremental.cells.len() + { + return Err(ResidentExpertSourceError::Geometry); + } + for cell in &incremental.cells { + if !incremental_cell_complete(cell, source)? { + return Err(ResidentExpertSourceError::Geometry); + } + } + Ok(()) + } +} + +fn incremental_cell_complete( + cell: &IncrementalTensor, + source: &VerifiedGgufFile, +) -> Result { + Ok(cell.covered == cell.descriptor.bytes + && cell.bytes.len() == cell.descriptor.bytes + && cell.bytes.capacity() == cell.charged_bytes + && provisional_descriptor(source.index(), cell.descriptor.role)? == cell.descriptor) } impl Qwen4ExpArtifact { /// Separately selected incremental capture; original prezeroed API remains. diff --git a/crates/model-format/src/qwen4exp_digest_capture/impl_qwen4expartifact.rs b/crates/model-format/src/qwen4exp_digest_capture/impl_qwen4expartifact.rs index 61f3c04b..84b933a2 100644 --- a/crates/model-format/src/qwen4exp_digest_capture/impl_qwen4expartifact.rs +++ b/crates/model-format/src/qwen4exp_digest_capture/impl_qwen4expartifact.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: impl Qwen4ExpArtifact, impl ProvisionalExpertSource, impl IncrementalCapture. +//! Moved out of the parent module by STRA-338: impl Qwen4ExpArtifact, impl ProvisionalExpertSource, impl +//! IncrementalCapture. #[allow(unused_imports)] use super::*; @@ -19,6 +20,16 @@ impl Qwen4ExpArtifact { &mut self, mut capture: ProvisionalExpertSource, ) -> Result { + self.check_capture_admissible(&mut capture)?; + let identity = self.revalidate_capture(&capture)?; + let observed = charge_retention(&mut capture)?; + self.mint_banks(&mut capture, identity)?; + capture_admit(0, 0, memory_available()?)?; + Ok(self.publish_resident_experts(capture, observed)) + } + + /// The model is not already enabled and fits the closed layout, and the capture ended without error. + fn check_capture_admissible(&self, capture: &mut ProvisionalExpertSource) -> Result<(), ResidentExpertSourceError> { if self.resident_experts.is_some() { return Err(ResidentExpertSourceError::AlreadyEnabled); } @@ -31,40 +42,55 @@ impl Qwen4ExpArtifact { if capture.cells.len() != BANKS || !capture.banks.is_empty() || capture.charged as u64 > SOURCE_CAP { return Err(ResidentExpertSourceError::Geometry); } + Ok(()) + } + + /// Revalidate EVERY bound descriptor before minting even the first final + /// tensor. Full finite admission still happens at each selected role. + fn revalidate_capture(&mut self, capture: &ProvisionalExpertSource) -> Result { let identity = capture.source.ok_or(ResidentExpertSourceError::Geometry)?; self.shards[0] .validate_capture_identity(identity) .map_err(|error| ResidentExpertSourceError::Read(BindingError::Io(error)))?; - // Revalidate EVERY bound descriptor before minting even the first final - // tensor. Full finite admission still happens at each selected role. for (number, cell) in capture.cells.iter().enumerate() { - let resolved = self.roles.get(&cell.descriptor.role).ok_or(ResidentExpertSourceError::Geometry)?; - if slot(cell.descriptor.role).map_err(ResidentExpertSourceError::Read)? != number - || checked_descriptor(cell.descriptor.role, resolved)? != cell.descriptor - || cell.covered != cell.bytes.len() - { - return Err(ResidentExpertSourceError::Geometry); - } - self.shards[0] - .stream_tensor(cell.descriptor.tensor_number, 0, 0, |_| Ok(())) - .map_err(|error| ResidentExpertSourceError::Read(BindingError::Io(error)))?; + self.revalidate_cell(number, cell)?; } - // Existing captured Boxes stay in place. Charge only the new small - // shared owners/directory before any wrapping/publication. - let retention = retention_metadata_bytes()?; - capture.charged = capture.charged.checked_add(retention).ok_or(ResidentExpertSourceError::MemoryAdmission)?; - if capture.charged as u64 > SOURCE_CAP { - return Err(ResidentExpertSourceError::MemoryAdmission); + Ok(identity) + } + + fn revalidate_cell(&mut self, number: usize, cell: &CapturedTensor) -> Result<(), ResidentExpertSourceError> { + let resolved = self.roles.get(&cell.descriptor.role).ok_or(ResidentExpertSourceError::Geometry)?; + if slot(cell.descriptor.role).map_err(ResidentExpertSourceError::Read)? != number + || checked_descriptor(cell.descriptor.role, resolved)? != cell.descriptor + || cell.covered != cell.bytes.len() + { + return Err(ResidentExpertSourceError::Geometry); } - let observed = memory_available()?; - capture_admit(retention, 0, observed)?; // payload pages already resident - for cell in capture.cells { + self.shards[0] + .stream_tensor(cell.descriptor.tensor_number, 0, 0, |_| Ok(())) + .map_err(|error| ResidentExpertSourceError::Read(BindingError::Io(error))) + } + + /// Existing captured Boxes stay in place: each becomes a retained bank tensor of the source. + fn mint_banks( + &mut self, + capture: &mut ProvisionalExpertSource, + identity: u64, + ) -> Result<(), ResidentExpertSourceError> { + for cell in std::mem::take(&mut capture.cells) { let tensor = self.shards[0] .admit_captured_tensor(identity, cell.descriptor.tensor_number, cell.bytes, cell.charged_bytes) .map_err(|error| ResidentExpertSourceError::Read(BindingError::Io(error)))?; capture.banks.push(Bank { descriptor: cell.descriptor, tensor: tensor.into_retained() }); } - capture_admit(0, 0, memory_available()?)?; + Ok(()) + } + + fn publish_resident_experts( + &mut self, + capture: ProvisionalExpertSource, + observed: usize, + ) -> ResidentExpertSourceReport { let report = ResidentExpertSourceReport { source_bytes: capture.source_bytes as u64, charged_bytes: capture.charged as u64, @@ -83,10 +109,23 @@ impl Qwen4ExpArtifact { copied_spans: Cell::new(0), copied_bytes: Cell::new(0), }); - Ok(report) + report } } +/// Charge only the new small shared owners/directory before any wrapping/publication; returns the observed +/// available memory. +fn charge_retention(capture: &mut ProvisionalExpertSource) -> Result { + let retention = retention_metadata_bytes()?; + capture.charged = capture.charged.checked_add(retention).ok_or(ResidentExpertSourceError::MemoryAdmission)?; + if capture.charged as u64 > SOURCE_CAP { + return Err(ResidentExpertSourceError::MemoryAdmission); + } + let observed = memory_available()?; + capture_admit(retention, 0, observed)?; // payload pages already resident + Ok(observed) +} + #[cfg(test)] impl ProvisionalExpertSource { pub(crate) fn test_cells(index: &TensorIndex) -> Self { @@ -157,36 +196,70 @@ impl IncrementalCapture { let end = position.checked_add(chunk.len() as u64).ok_or(ResidentExpertSourceError::Geometry)?; let mut remaining = self.remaining_commitment()?; for cell in &mut self.cells { - let start = cell.descriptor.absolute_start; - let bank_end = - start.checked_add(cell.descriptor.bytes as u64).ok_or(ResidentExpertSourceError::Geometry)?; - let left = start.max(position); - let right = bank_end.min(end); - if left >= right { + let Some(span) = cell_overlap(cell, position, end)? else { continue; - } - let offset = usize::try_from(left - start).map_err(|_| ResidentExpertSourceError::Geometry)?; - let count = usize::try_from(right - left).map_err(|_| ResidentExpertSourceError::Geometry)?; - let next = offset.checked_add(count).ok_or(ResidentExpertSourceError::Geometry)?; - if offset != cell.covered - || offset != cell.bytes.len() - || next > cell.descriptor.bytes - || next > cell.bytes.capacity() - { - return Err(ResidentExpertSourceError::Geometry); - } - let source = usize::try_from(left - position).map_err(|_| ResidentExpertSourceError::Geometry)?; - let selected = chunk - .get(source..source.checked_add(count).ok_or(ResidentExpertSourceError::Geometry)?) - .ok_or(ResidentExpertSourceError::Geometry)?; - // Actual snapshot immediately BEFORE touching this span. All other - // reserved banks and capacity slack stay committed; no VM credit. - let next_remaining = remaining.checked_sub(count).ok_or(ResidentExpertSourceError::MemoryAdmission)?; - capture_admit(remaining, FUTURE_OWNERS, available()?)?; - cell.bytes.extend_from_slice(selected); // proven within reservation - cell.covered = next; - remaining = next_remaining; + }; + remaining = append_span(cell, &span, chunk, remaining, &mut available)?; } Ok(()) } } + +/// The part of a chunk that falls inside one cell: where it goes in the cell, how long it is, where it starts in the +/// chunk. +struct ChunkSpan { + offset: usize, + count: usize, + source: usize, + next: usize, +} + +fn cell_overlap( + cell: &IncrementalTensor, + position: u64, + end: u64, +) -> Result, ResidentExpertSourceError> { + let start = cell.descriptor.absolute_start; + let bank_end = start.checked_add(cell.descriptor.bytes as u64).ok_or(ResidentExpertSourceError::Geometry)?; + let left = start.max(position); + let right = bank_end.min(end); + if left >= right { + return Ok(None); + } + let offset = usize::try_from(left - start).map_err(|_| ResidentExpertSourceError::Geometry)?; + let count = usize::try_from(right - left).map_err(|_| ResidentExpertSourceError::Geometry)?; + let next = offset.checked_add(count).ok_or(ResidentExpertSourceError::Geometry)?; + let source = usize::try_from(left - position).map_err(|_| ResidentExpertSourceError::Geometry)?; + Ok(Some(ChunkSpan { offset, count, source, next })) +} + +/// The span continues exactly where the cell stopped, inside the descriptor and the reservation. +fn span_fits(cell: &IncrementalTensor, span: &ChunkSpan) -> bool { + span.offset == cell.covered + && span.offset == cell.bytes.len() + && span.next <= cell.descriptor.bytes + && span.next <= cell.bytes.capacity() +} + +/// Appends the span to the cell after the memory admission; returns the commitment that is left. +fn append_span( + cell: &mut IncrementalTensor, + span: &ChunkSpan, + chunk: &[u8], + remaining: usize, + available: &mut impl FnMut() -> Result, +) -> Result { + if !span_fits(cell, span) { + return Err(ResidentExpertSourceError::Geometry); + } + let selected = chunk + .get(span.source..span.source.checked_add(span.count).ok_or(ResidentExpertSourceError::Geometry)?) + .ok_or(ResidentExpertSourceError::Geometry)?; + // Actual snapshot immediately BEFORE touching this span. All other + // reserved banks and capacity slack stay committed; no VM credit. + let next_remaining = remaining.checked_sub(span.count).ok_or(ResidentExpertSourceError::MemoryAdmission)?; + capture_admit(remaining, FUTURE_OWNERS, available()?)?; + cell.bytes.extend_from_slice(selected); // proven within reservation + cell.covered = span.next; + Ok(next_remaining) +} diff --git a/crates/model-format/src/qwen4exp_digest_capture_incremental_sdet.rs b/crates/model-format/src/qwen4exp_digest_capture_incremental_sdet.rs index 66959942..c60c2ee1 100644 --- a/crates/model-format/src/qwen4exp_digest_capture_incremental_sdet.rs +++ b/crates/model-format/src/qwen4exp_digest_capture_incremental_sdet.rs @@ -73,9 +73,24 @@ fn two_spans(index: &gguf::TensorIndex) -> ProvisionalExpertSource { #[test] fn original_zeroed_stream_first_incremental_spans_bytes_commitment_and_refusal() { let fixture = Fixture::new(); - // ORIGINAL strict whole SHA/index + real FD stream FIRST, with the old - // zeroed destination and copy ordering, before constructing the candidate. let mut original = VerifiedGgufFile::open(&fixture.path, &fixture.digest()).unwrap(); + let expected = stream_expected(&mut original); + let index_owner = VerifiedGgufFile::open(&fixture.path, &fixture.digest()).unwrap(); + let index = index_owner.index(); + check_chunk_widths(&fixture, index, &expected); + let start = index.summary.data_start; + let payload = &fixture.bytes[start as usize..]; + check_partial_observation(index, (start, payload), &expected, &mut original); + let exact = check_exact_commitment(index, (start, payload), &expected); + check_discarded_captures(index, (start, payload)); + check_crossing_snapshots(index, (start, payload), &expected, exact); + check_source_capability(&fixture, index, (start, payload), &expected, &mut original); + check_admission_limits(); +} + +/// ORIGINAL strict whole SHA/index + real FD stream FIRST, with the old +/// zeroed destination and copy ordering, before constructing the candidate. +fn stream_expected(original: &mut VerifiedGgufFile) -> Vec> { let extents: Vec<_> = original.index().tensors.iter().map(|tensor| tensor.bytes).collect(); let mut expected = Vec::new(); for (number, extent) in extents.into_iter().enumerate() { @@ -91,12 +106,12 @@ fn original_zeroed_stream_first_incremental_spans_bytes_commitment_and_refusal() assert_eq!(copied, zeroed.len()); expected.push(zeroed); } + expected +} - let index_owner = VerifiedGgufFile::open(&fixture.path, &fixture.digest()).unwrap(); - let index = index_owner.index(); - - // Genuine indexed spans cross one another and stream chunks. The injected - // snapshot is only a numeric fixture input, never a physical/model proof. +/// Genuine indexed spans cross one another and stream chunks. The injected +/// snapshot is only a numeric fixture input, never a physical/model proof. +fn check_chunk_widths(fixture: &Fixture, index: &gguf::TensorIndex, expected: &[Vec]) { for width in [1usize, 7, 63, 64, 65, fixture.bytes.len() + 1] { let mut capture = two_spans(index); let pointers: Vec<_> = @@ -117,16 +132,23 @@ fn original_zeroed_stream_first_incremental_spans_bytes_commitment_and_refusal() } assert_eq!(capture.test_remaining_commitment().unwrap(), capacities.iter().sum::() - 160); } +} - let start = index.summary.data_start; - let payload = &fixture.bytes[start as usize..]; +fn check_partial_observation( + index: &gguf::TensorIndex, + (start, payload): (u64, &[u8]), + expected: &[Vec], + original: &mut VerifiedGgufFile, +) { let mut partial = ProvisionalExpertSource::test_incremental_cells(index); partial.observe(start, &payload[..31]); assert_eq!(partial.incremental.as_ref().unwrap().cells[0].bytes, expected[0][..31]); assert!(partial.test_incremental_bytes().is_none()); - assert!(partial.test_incremental_mint(&mut original).is_err()); // len==covered isn't full + assert!(partial.test_incremental_mint(original).is_err()); // len==covered isn't full +} - // Exact remaining capacity includes the other untouched span and any slack. +/// Exact remaining capacity includes the other untouched span and any slack; returns the exact admitting snapshot. +fn check_exact_commitment(index: &gguf::TensorIndex, (start, payload): (u64, &[u8]), expected: &[Vec]) -> usize { let mut admitted = two_spans(index); let untouched = admitted.test_remaining_commitment().unwrap(); let headroom = usize::try_from(FUTURE_HEADROOM).unwrap(); @@ -146,6 +168,17 @@ fn original_zeroed_stream_first_incremental_spans_bytes_commitment_and_refusal() assert_eq!(admitted.incremental.as_ref().unwrap().cells[0].bytes, expected[0]); assert_eq!(admitted.incremental.as_ref().unwrap().cells[0].bytes.as_ptr(), before[0]); assert_eq!(admitted.incremental.as_ref().unwrap().cells[1].bytes.as_ptr(), before[1]); + check_second_span(&mut admitted, (start, payload), expected, exact); + exact +} + +/// The second span takes exactly one memory snapshot for the rest of the payload. +fn check_second_span( + admitted: &mut ProvisionalExpertSource, + (start, payload): (u64, &[u8]), + expected: &[Vec], + exact: usize, +) { let mut checks = 0; admitted .test_observe_inner(start + 64, &payload[64..], || { @@ -155,8 +188,10 @@ fn original_zeroed_stream_first_incremental_spans_bytes_commitment_and_refusal() .unwrap(); assert_eq!(checks, 1); assert_eq!(admitted.incremental.as_ref().unwrap().cells[1].bytes, expected[1]); - drop(admitted); +} +/// Gaps, repeats and failed snapshots discard the capture. +fn check_discarded_captures(index: &gguf::TensorIndex, (start, payload): (u64, &[u8])) { for (position, selected) in [(start + 1, &payload[1..5]), (u64::MAX, &payload[..2])] { let mut refused = two_spans(index); refused.observe(position, selected); @@ -173,6 +208,15 @@ fn original_zeroed_stream_first_incremental_spans_bytes_commitment_and_refusal() assert!(failed_snapshot.incremental.as_ref().unwrap().cells.iter().all(|cell| cell.bytes.is_empty())); failed_snapshot.fail(ResidentExpertSourceError::MemoryAdmission); assert!(failed_snapshot.test_discarded()); +} + +/// A snapshot that fails after the first span leaves that span written and the second untouched. +fn check_crossing_snapshots( + index: &gguf::TensorIndex, + (start, payload): (u64, &[u8]), + expected: &[Vec], + exact: usize, +) { let mut crossing = two_spans(index); let mut snapshots = 0; let later_error = crossing.test_observe_inner(start, payload, || { @@ -185,12 +229,20 @@ fn original_zeroed_stream_first_incremental_spans_bytes_commitment_and_refusal() assert!(crossing.incremental.as_ref().unwrap().cells[1].bytes.is_empty()); crossing.fail(ResidentExpertSourceError::MemoryAdmission); assert!(crossing.test_discarded()); // actual wrapper drops partial owners +} - // Full actual source capability after complete transport only. Path aliases - // cannot replace the owned source; genuine foreign and size change refuse. +/// Full actual source capability after complete transport only. Path aliases +/// cannot replace the owned source; genuine foreign and size change refuse. +fn check_source_capability( + fixture: &Fixture, + index: &gguf::TensorIndex, + (start, payload): (u64, &[u8]), + expected: &[Vec], + original: &mut VerifiedGgufFile, +) { let mut full = ProvisionalExpertSource::test_incremental_cells(index); full.observe(start, &payload[..64]); - let resident = full.test_incremental_mint(&mut original).unwrap(); + let resident = full.test_incremental_mint(original).unwrap(); assert_eq!(&*original.copy_resident_tensor(&resident, 0, vec![0; 64].into_boxed_slice()).unwrap(), &expected[0]); let foreign = VerifiedGgufFile::open(&fixture.path, &fixture.digest()).unwrap(); assert!(foreign.copy_resident_tensor(&resident, 0, vec![0; 64].into_boxed_slice()).is_err()); @@ -203,15 +255,10 @@ fn original_zeroed_stream_first_incremental_spans_bytes_commitment_and_refusal() assert_eq!(old_error, capture_error); // deferred capture cannot outrank SHA std::fs::OpenOptions::new().write(true).open(&fixture.path).unwrap().set_len(1).unwrap(); assert!(original.copy_resident_tensor(&resident, 0, vec![0; 64].into_boxed_slice()).is_err()); - drop(resident); - drop(foreign); - drop(index_owner); - drop(original); - drop(crossing); - drop(failed_snapshot); - drop(repeated); - drop(fixture); +} +fn check_admission_limits() { + let headroom = usize::try_from(FUTURE_HEADROOM).unwrap(); let cap = usize::try_from(SOURCE_CAP).unwrap(); assert!(capture_admit(cap, FUTURE_OWNERS, cap + FUTURE_OWNERS + headroom).is_ok()); assert!(capture_admit(cap + 1, 0, usize::MAX).is_err()); diff --git a/crates/model-format/src/qwen4exp_expert_source_bank/impl_qwen4expartifact.rs b/crates/model-format/src/qwen4exp_expert_source_bank/impl_qwen4expartifact.rs index 12443d0e..aaa5f274 100644 --- a/crates/model-format/src/qwen4exp_expert_source_bank/impl_qwen4expartifact.rs +++ b/crates/model-format/src/qwen4exp_expert_source_bank/impl_qwen4expartifact.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: impl Qwen4ExpArtifact, impl ResidentExpertBankLease, impl ResidentExpertBankMember. +//! Moved out of the parent module by STRA-338: impl Qwen4ExpArtifact, impl ResidentExpertBankLease, impl +//! ResidentExpertBankMember. #[allow(unused_imports)] use super::*; @@ -7,36 +8,51 @@ impl Qwen4ExpArtifact { /// Explicit fresh-owner load; called before publishing a selected binding. /// No tensor finite admission is performed on unused expert banks. pub fn load_resident_expert_source(&mut self) -> Result { + self.check_expert_layout()?; + let mut plan = Vec::new(); + plan.try_reserve_exact(BANKS).map_err(|_| ResidentExpertSourceError::Allocation)?; + let mut banks = Vec::new(); + banks.try_reserve_exact(BANKS).map_err(|_| ResidentExpertSourceError::Allocation)?; + let metadata = resident_metadata_bytes(plan.capacity(), banks.capacity())?; + let source_bytes = self.plan_banks(&mut plan)?; + let observed = admit_plan(source_bytes, metadata)?; + let (charged, remaining) = self.load_banks(plan, &mut banks, metadata, source_bytes)?; + self.verify_loaded_banks(&banks, remaining)?; + let report = self.bank_report(source_bytes, charged, observed, FUTURE_HEADROOM, false); + Ok(self.publish_banks(banks, report)) + } + + /// The model is not already enabled and has the closed expert layout. + fn check_expert_layout(&self) -> Result<(), ResidentExpertSourceError> { if self.resident_experts.is_some() { return Err(ResidentExpertSourceError::AlreadyEnabled); } if self.topology.block_count != 48 || self.topology.expert_count != 512 { return Err(ResidentExpertSourceError::Geometry); } - let mut plan = Vec::new(); - plan.try_reserve_exact(BANKS).map_err(|_| ResidentExpertSourceError::Allocation)?; - let mut banks = Vec::new(); - banks.try_reserve_exact(BANKS).map_err(|_| ResidentExpertSourceError::Allocation)?; - let metadata = plan - .capacity() - .checked_mul(size_of::()) - .and_then(|v| v.checked_add(banks.capacity().checked_mul(size_of::())?)) - .and_then(|v| v.checked_add(size_of::() + 2 * size_of::())) - .and_then(|v| v.checked_add(retention_metadata_bytes().ok()?)) - .ok_or(ResidentExpertSourceError::Geometry)?; + Ok(()) + } + + /// The descriptor of every expert tensor, in bank order, pushed on `plan`; returns their total bytes. + fn plan_banks(&self, plan: &mut Vec) -> Result { let mut source_bytes = 0usize; - for layer in 0..48 { - for role in [LayerRole::FfnGateExperts, LayerRole::FfnUpExperts, LayerRole::FfnDownExperts] { - let role = TensorRole::Layer { layer, role }; - let tensor = self.roles.get(&role).ok_or(ResidentExpertSourceError::Geometry)?; - let descriptor = checked_descriptor(role, tensor)?; - source_bytes = source_bytes.checked_add(descriptor.bytes).ok_or(ResidentExpertSourceError::Geometry)?; - plan.push(descriptor); - } + for role in expert_roles() { + let tensor = self.roles.get(&role).ok_or(ResidentExpertSourceError::Geometry)?; + let descriptor = checked_descriptor(role, tensor)?; + source_bytes = source_bytes.checked_add(descriptor.bytes).ok_or(ResidentExpertSourceError::Geometry)?; + plan.push(descriptor); } - let planned = source_bytes.checked_add(metadata).ok_or(ResidentExpertSourceError::Geometry)?; - let observed = memory_available()?; - admit(planned, observed)?; + Ok(source_bytes) + } + + /// Reads every planned tensor into a resident bank under the memory admission; returns (charged, remaining) bytes. + fn load_banks( + &mut self, + plan: Vec, + banks: &mut Vec, + metadata: usize, + source_bytes: usize, + ) -> Result<(usize, usize), ResidentExpertSourceError> { let mut charged = metadata; let mut remaining = source_bytes; for descriptor in plan { @@ -46,16 +62,9 @@ impl Qwen4ExpArtifact { SOURCE_CAP.checked_sub(charged as u64).ok_or(ResidentExpertSourceError::MemoryAdmission)?, ) .map_err(|_| ResidentExpertSourceError::MemoryAdmission)?; - let tensor = - self.shards[0].load_resident_tensor(descriptor.tensor_number, ceiling).map_err( - |error| match error { - gguf::ResidentLoadError::Allocation => ResidentExpertSourceError::Allocation, - gguf::ResidentLoadError::Budget => ResidentExpertSourceError::MemoryAdmission, - gguf::ResidentLoadError::Source(error) => { - ResidentExpertSourceError::Read(BindingError::Io(error)) - } - }, - )?; + let tensor = self.shards[0] + .load_resident_tensor(descriptor.tensor_number, ceiling) + .map_err(load_error_to_source_error)?; charged = charged.checked_add(tensor.charged_bytes()).ok_or(ResidentExpertSourceError::MemoryAdmission)?; if charged as u64 > SOURCE_CAP { return Err(ResidentExpertSourceError::MemoryAdmission); @@ -63,7 +72,11 @@ impl Qwen4ExpArtifact { remaining = remaining.checked_sub(descriptor.bytes).ok_or(ResidentExpertSourceError::Geometry)?; banks.push(Bank { descriptor, tensor: tensor.into_retained() }); } - // Bank publication itself retains the same current-source refusal. + Ok((charged, remaining)) + } + + /// Bank publication itself retains the same current-source refusal. + fn verify_loaded_banks(&mut self, banks: &[Bank], remaining: usize) -> Result<(), ResidentExpertSourceError> { let last = banks.last().ok_or(ResidentExpertSourceError::Geometry)?; self.shards[0] .stream_tensor(last.descriptor.tensor_number, 0, 0, |_| Ok(())) @@ -72,26 +85,41 @@ impl Qwen4ExpArtifact { if remaining != 0 || banks.len() != BANKS { return Err(ResidentExpertSourceError::Geometry); } - let report = ResidentExpertSourceReport { + Ok(()) + } + + fn bank_report( + &self, + source_bytes: usize, + charged: usize, + observed: usize, + headroom: u64, + file_mapped: bool, + ) -> ResidentExpertSourceReport { + ResidentExpertSourceReport { source_bytes: source_bytes as u64, charged_bytes: charged as u64, bank_count: BANKS as u32, source_cap_bytes: SOURCE_CAP, observed_mem_available_bytes: observed as u64, - future_headroom_bytes: FUTURE_HEADROOM, + future_headroom_bytes: headroom, shard0_sha256: self.shards[0].artifact_sha256(), copied_spans: 0, copied_bytes: 0, - file_mapped: false, - }; + file_mapped, + } + } + + fn publish_banks(&mut self, banks: Vec, report: ResidentExpertSourceReport) -> ResidentExpertSourceReport { self.resident_experts = Some(ResidentExpertBank { banks: Rc::new(banks), report, copied_spans: Cell::new(0), copied_bytes: Cell::new(0), }); - Ok(report) + report } + pub fn resident_expert_source_report(&self) -> Option { self.resident_experts.as_ref().map(|bank| bank.report()) } @@ -103,61 +131,62 @@ impl Qwen4ExpArtifact { /// sees exactly what the resident copy would hold. No `MemAvailable` admission: the mapping commits no RAM. #[cfg(any(target_os = "linux", windows))] pub fn load_mapped_expert_source(&mut self) -> Result { - if self.resident_experts.is_some() { - return Err(ResidentExpertSourceError::AlreadyEnabled); - } - if self.topology.block_count != 48 || self.topology.expert_count != 512 { - return Err(ResidentExpertSourceError::Geometry); - } + self.check_expert_layout()?; let mut banks = Vec::new(); banks.try_reserve_exact(BANKS).map_err(|_| ResidentExpertSourceError::Allocation)?; let mut source_bytes = 0usize; - for layer in 0..48 { - for role in [LayerRole::FfnGateExperts, LayerRole::FfnUpExperts, LayerRole::FfnDownExperts] { - let role = TensorRole::Layer { layer, role }; - let tensor = self.roles.get(&role).ok_or(ResidentExpertSourceError::Geometry)?; - let descriptor = checked_descriptor(role, tensor)?; - source_bytes = source_bytes.checked_add(descriptor.bytes).ok_or(ResidentExpertSourceError::Geometry)?; - if source_bytes as u64 > SOURCE_CAP { - return Err(ResidentExpertSourceError::MemoryAdmission); - } - let mapped = - self.shards[0].map_resident_tensor(descriptor.tensor_number).map_err(|error| match error { - gguf::ResidentLoadError::Allocation => ResidentExpertSourceError::Allocation, - gguf::ResidentLoadError::Budget => ResidentExpertSourceError::MemoryAdmission, - gguf::ResidentLoadError::Source(error) => { - ResidentExpertSourceError::Read(BindingError::Io(error)) - } - })?; - if mapped.len() != descriptor.bytes { - return Err(ResidentExpertSourceError::Geometry); - } - banks.push(Bank { descriptor, tensor: mapped.into_retained() }); + for role in expert_roles() { + let tensor = self.roles.get(&role).ok_or(ResidentExpertSourceError::Geometry)?; + let descriptor = checked_descriptor(role, tensor)?; + source_bytes = source_bytes.checked_add(descriptor.bytes).ok_or(ResidentExpertSourceError::Geometry)?; + if source_bytes as u64 > SOURCE_CAP { + return Err(ResidentExpertSourceError::MemoryAdmission); } + banks.push(self.map_bank(descriptor)?); } if banks.len() != BANKS { return Err(ResidentExpertSourceError::Geometry); } - let report = ResidentExpertSourceReport { - source_bytes: source_bytes as u64, - charged_bytes: source_bytes as u64, - bank_count: BANKS as u32, - source_cap_bytes: SOURCE_CAP, - observed_mem_available_bytes: 0, - future_headroom_bytes: 0, - shard0_sha256: self.shards[0].artifact_sha256(), - copied_spans: 0, - copied_bytes: 0, - file_mapped: true, - }; - self.resident_experts = Some(ResidentExpertBank { - banks: Rc::new(banks), - report, - copied_spans: Cell::new(0), - copied_bytes: Cell::new(0), - }); - Ok(report) + let report = self.bank_report(source_bytes, source_bytes, 0, 0, true); + Ok(self.publish_banks(banks, report)) } + + /// One bank as a read-only mapping of the tensor in shard 0. + #[cfg(any(target_os = "linux", windows))] + fn map_bank(&mut self, descriptor: BankDescriptor) -> Result { + let mapped = + self.shards[0].map_resident_tensor(descriptor.tensor_number).map_err(load_error_to_source_error)?; + if mapped.len() != descriptor.bytes { + return Err(ResidentExpertSourceError::Geometry); + } + Ok(Bank { descriptor, tensor: mapped.into_retained() }) + } +} + +fn load_error_to_source_error(error: gguf::ResidentLoadError) -> ResidentExpertSourceError { + match error { + gguf::ResidentLoadError::Allocation => ResidentExpertSourceError::Allocation, + gguf::ResidentLoadError::Budget => ResidentExpertSourceError::MemoryAdmission, + gguf::ResidentLoadError::Source(error) => ResidentExpertSourceError::Read(BindingError::Io(error)), + } +} + +/// The bytes of the plan, bank and retention tables (of the given capacities), charged before anything is read. +fn resident_metadata_bytes(plan_capacity: usize, banks_capacity: usize) -> Result { + plan_capacity + .checked_mul(size_of::()) + .and_then(|v| v.checked_add(banks_capacity.checked_mul(size_of::())?)) + .and_then(|v| v.checked_add(size_of::() + 2 * size_of::())) + .and_then(|v| v.checked_add(retention_metadata_bytes().ok()?)) + .ok_or(ResidentExpertSourceError::Geometry) +} + +/// The memory admission of the whole plan; returns the observed available memory. +fn admit_plan(source_bytes: usize, metadata: usize) -> Result { + let planned = source_bytes.checked_add(metadata).ok_or(ResidentExpertSourceError::Geometry)?; + let observed = memory_available()?; + admit(planned, observed)?; + Ok(observed) } impl ResidentExpertBankLease { pub fn bank_count(&self) -> usize { diff --git a/crates/model-format/src/qwen4exp_expert_source_bank/impl_qwen4expartifact_2.rs b/crates/model-format/src/qwen4exp_expert_source_bank/impl_qwen4expartifact_2.rs index d0710d43..c4a40b37 100644 --- a/crates/model-format/src/qwen4exp_expert_source_bank/impl_qwen4expartifact_2.rs +++ b/crates/model-format/src/qwen4exp_expert_source_bank/impl_qwen4expartifact_2.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: impl Qwen4ExpArtifact, impl ResidentExpertBankSpan, impl ResidentExpertBank. +//! Moved out of the parent module by STRA-338: impl Qwen4ExpArtifact, impl ResidentExpertBankSpan, impl +//! ResidentExpertBank. #[allow(unused_imports)] use super::*; @@ -7,8 +8,7 @@ impl Qwen4ExpArtifact { /// Short actual artifact borrow; result owns all144 existing allocations. pub fn resident_expert_bank_lease(&self) -> Result { let bank = self.resident_experts.as_ref().ok_or(BindingError::Role("resident_expert_source_absent"))?; - if bank.banks.len() != BANKS || bank.report.bank_count != BANKS as u32 || bank.report.charged_bytes > SOURCE_CAP - { + if !bank_directory_ok(bank) { return Err(BindingError::Geometry("resident_expert_directory")); } for (number, member) in bank.banks.iter().enumerate() { @@ -42,6 +42,11 @@ impl Qwen4ExpArtifact { Ok(ResidentExpertBankMember { descriptor: member.descriptor, tensor: Rc::clone(&member.tensor) }) } } +/// The bank holds all 144 members and charged no more than the source cap. +fn bank_directory_ok(bank: &ResidentExpertBank) -> bool { + bank.banks.len() == BANKS && bank.report.bank_count == BANKS as u32 && bank.report.charged_bytes <= SOURCE_CAP +} + impl ResidentExpertBankSpan { pub fn bytes(&self) -> &[u8] { &self.member.bytes()[self.offset..self.offset + self.length] diff --git a/crates/model-format/src/qwen4exp_expert_source_bank/retention_metadata_bytes.rs b/crates/model-format/src/qwen4exp_expert_source_bank/retention_metadata_bytes.rs index 3aa3a194..6123e765 100644 --- a/crates/model-format/src/qwen4exp_expert_source_bank/retention_metadata_bytes.rs +++ b/crates/model-format/src/qwen4exp_expert_source_bank/retention_metadata_bytes.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: fn retention_metadata_bytes, impl fmt_Display_for, impl Error_for_ResidentExpertSourceError, fn checked_descriptor, fn slot, fn memory_available .... +//! Moved out of the parent module by STRA-338: fn retention_metadata_bytes, impl fmt_Display_for, impl +//! Error_for_ResidentExpertSourceError, fn checked_descriptor, fn slot, fn memory_available .... #[allow(unused_imports)] use super::*; @@ -21,17 +22,35 @@ pub(super) fn checked_descriptor( role: TensorRole, tensor: &ResolvedTensor, ) -> Result { - use LayerRole as L; - let (columns, rows, kinds): (u64, u64, &[u32]) = match role { - TensorRole::Layer { layer, role: L::FfnGateExperts | L::FfnUpExperts } if layer < 48 => { - (2560, 640, &[18, 21, 22, 23]) - } - TensorRole::Layer { layer, role: L::FfnDownExperts } if layer < 48 => (640, 2560, &[20, 42]), - _ => return Err(ResidentExpertSourceError::Geometry), - }; + let (columns, rows, kinds) = expert_shape(role)?; if tensor.shard != 0 || tensor.dimensions != [columns, rows, 512] || !kinds.contains(&tensor.kind) { return Err(ResidentExpertSourceError::Geometry); } + check_expert_strides(role, tensor, rows)?; + Ok(BankDescriptor { + role, + tensor_number: tensor.tensor_number, + raw_kind: tensor.kind, + absolute_start: tensor.absolute_start, + file_size: tensor.file_size, + bytes: usize::try_from(tensor.byte_length).map_err(|_| ResidentExpertSourceError::Geometry)?, + }) +} + +/// (columns, rows, admitted GGUF kinds) of the routed-expert tensor of a role. +fn expert_shape(role: TensorRole) -> Result<(u64, u64, &'static [u32]), ResidentExpertSourceError> { + use LayerRole as L; + match role { + TensorRole::Layer { layer, role: L::FfnGateExperts | L::FfnUpExperts } if layer < 48 => { + Ok((2560, 640, &[18, 21, 22, 23])) + } + TensorRole::Layer { layer, role: L::FfnDownExperts } if layer < 48 => Ok((640, 2560, &[20, 42])), + _ => Err(ResidentExpertSourceError::Geometry), + } +} + +/// The 512 experts are equal, contiguous spans that fill the tensor exactly. +fn check_expert_strides(role: TensorRole, tensor: &ResolvedTensor, rows: u64) -> Result<(), ResidentExpertSourceError> { let first = plan_stream_rows(tensor, role, 0, rows, Some(0)).map_err(|_| ResidentExpertSourceError::Geometry)?; let last = plan_stream_rows(tensor, role, 0, rows, Some(511)).map_err(|_| ResidentExpertSourceError::Geometry)?; if first.0 != 0 @@ -43,14 +62,7 @@ pub(super) fn checked_descriptor( { return Err(ResidentExpertSourceError::Geometry); } - Ok(BankDescriptor { - role, - tensor_number: tensor.tensor_number, - raw_kind: tensor.kind, - absolute_start: tensor.absolute_start, - file_size: tensor.file_size, - bytes: usize::try_from(tensor.byte_length).map_err(|_| ResidentExpertSourceError::Geometry)?, - }) + Ok(()) } pub(super) fn slot(role: TensorRole) -> Result { let (layer, role) = match role { @@ -67,61 +79,34 @@ pub(super) fn slot(role: TensorRole) -> Result { } // Existing resident KAR and other owners are already reflected in MemAvailable. // This is a snapshot, never an allocation reservation or a guarantee against races. +#[cfg(target_os = "linux")] pub(super) fn memory_available() -> Result { - #[cfg(target_os = "linux")] - { - let mut text = String::new(); - File::open("/proc/meminfo") - .map_err(|_| ResidentExpertSourceError::MemoryAdmission)? - .take(65537) - .read_to_string(&mut text) - .map_err(|_| ResidentExpertSourceError::MemoryAdmission)?; - if text.len() > 65536 { - return Err(ResidentExpertSourceError::MemoryAdmission); - } - parse_memory_available(&text) - } - #[cfg(windows)] - { - let (total, available) = - leleka_libc_shim::physical_memory().ok_or(ResidentExpertSourceError::MemoryAdmission)?; - parse_memory_available(&format!( - "MemTotal: {} kB -MemAvailable: {} kB -", - total / 1024, - available / 1024 - )) - } - #[cfg(not(any(target_os = "linux", windows)))] - { - Err(ResidentExpertSourceError::MemoryAdmission) + let mut text = String::new(); + File::open("/proc/meminfo") + .map_err(|_| ResidentExpertSourceError::MemoryAdmission)? + .take(65537) + .read_to_string(&mut text) + .map_err(|_| ResidentExpertSourceError::MemoryAdmission)?; + if text.len() > 65536 { + return Err(ResidentExpertSourceError::MemoryAdmission); } + parse_memory_available(&text) +} +#[cfg(windows)] +pub(super) fn memory_available() -> Result { + let (total, available) = leleka_libc_shim::physical_memory().ok_or(ResidentExpertSourceError::MemoryAdmission)?; + parse_memory_available(&format!("MemTotal: {} kB\nMemAvailable: {} kB\n", total / 1024, available / 1024)) +} +#[cfg(not(any(target_os = "linux", windows)))] +pub(super) fn memory_available() -> Result { + Err(ResidentExpertSourceError::MemoryAdmission) } #[cfg(any(target_os = "linux", windows, test))] pub(super) fn parse_memory_available(text: &str) -> Result { let mut available = None; let mut total = None; for line in text.lines() { - let mut parts = line.split_ascii_whitespace(); - let Some(key) = parts.next() else { continue }; - let destination = match key { - "MemAvailable:" => &mut available, - "MemTotal:" => &mut total, - _ => continue, - }; - if destination.is_some() { - return Err(ResidentExpertSourceError::MemoryAdmission); - } - let value = parts - .next() - .ok_or(ResidentExpertSourceError::MemoryAdmission)? - .parse::() - .map_err(|_| ResidentExpertSourceError::MemoryAdmission)?; - if parts.next() != Some("kB") || parts.next().is_some() { - return Err(ResidentExpertSourceError::MemoryAdmission); - } - *destination = Some(value.checked_mul(1024).ok_or(ResidentExpertSourceError::MemoryAdmission)?); + read_meminfo_line(line, &mut available, &mut total)?; } let available = available.ok_or(ResidentExpertSourceError::MemoryAdmission)?; let total = total.ok_or(ResidentExpertSourceError::MemoryAdmission)?; @@ -130,6 +115,34 @@ pub(super) fn parse_memory_available(text: &str) -> Result, + total: &mut Option, +) -> Result<(), ResidentExpertSourceError> { + let mut parts = line.split_ascii_whitespace(); + let destination = match parts.next() { + Some("MemAvailable:") => available, + Some("MemTotal:") => total, + _ => return Ok(()), + }; + if destination.is_some() { + return Err(ResidentExpertSourceError::MemoryAdmission); + } + let value = parts + .next() + .ok_or(ResidentExpertSourceError::MemoryAdmission)? + .parse::() + .map_err(|_| ResidentExpertSourceError::MemoryAdmission)?; + if parts.next() != Some("kB") || parts.next().is_some() { + return Err(ResidentExpertSourceError::MemoryAdmission); + } + *destination = Some(value.checked_mul(1024).ok_or(ResidentExpertSourceError::MemoryAdmission)?); + Ok(()) +} pub(super) fn admit(capacity: usize, available: usize) -> Result<(), ResidentExpertSourceError> { if capacity as u64 > SOURCE_CAP || (capacity as u64).checked_add(FUTURE_HEADROOM).is_none_or(|n| n > available as u64) diff --git a/crates/model-format/src/qwen4exp_file_expert_source.rs b/crates/model-format/src/qwen4exp_file_expert_source.rs index 7e471d24..163ec373 100644 --- a/crates/model-format/src/qwen4exp_file_expert_source.rs +++ b/crates/model-format/src/qwen4exp_file_expert_source.rs @@ -70,25 +70,7 @@ impl Qwen4ExpArtifact { } for layer in 0..48u8 { for role in [LayerRole::FfnGateExperts, LayerRole::FfnUpExperts, LayerRole::FfnDownExperts] { - let named = TensorRole::Layer { layer, role }; - let tensor = self.roles.get(&named).ok_or(BindingError::Role("file_expert_role"))?; - // Reuse the actual routed bank shape/kind/domain admission; no wider stream geometry. - if tensor.shard != 0 || tensor.dimensions.len() != 3 || tensor.dimensions[2] != 512 { - return Err(BindingError::Geometry("file_expert_bank")); - } - let rows = if role == LayerRole::FfnDownExperts { 2560 } else { 640 }; - let (offset, length) = plan_stream_rows(tensor, named, 0, rows, Some(0))?; - if offset != 0 || length.checked_mul(512) != Some(tensor.byte_length) { - return Err(BindingError::Geometry("file_expert_bank")); - } - self.shards[0].validate_empty_tensor_source(tensor.tensor_number).map_err(BindingError::Io)?; - members.push(FileExpertExtent { - role: named, - absolute: tensor.absolute_start, - bytes: tensor.byte_length, - expert_bytes: usize::try_from(length).map_err(|_| BindingError::Range("file_expert_bytes"))?, - kind: tensor.kind, - }); + members.push(self.file_expert_extent(layer, role)?); } } let file = self.shards[0].expert_file_owner().map_err(BindingError::Io)?; @@ -102,6 +84,26 @@ impl Qwen4ExpArtifact { } Ok(FileExpertSourceLease { file, members, metadata_bytes }) } + + /// The extent of one routed-expert bank in the file, after the bank shape and stride admission. + fn file_expert_extent(&self, layer: u8, role: LayerRole) -> Result { + let named = TensorRole::Layer { layer, role }; + let tensor = self.roles.get(&named).ok_or(BindingError::Role("file_expert_role"))?; + // Reuse the actual routed bank shape/kind/domain admission; no wider stream geometry. + if tensor.shard != 0 || tensor.dimensions.len() != 3 || tensor.dimensions[2] != 512 { + return Err(BindingError::Geometry("file_expert_bank")); + } + let length = expert_stride(tensor, named, role)?; + self.shards[0].validate_empty_tensor_source(tensor.tensor_number).map_err(BindingError::Io)?; + Ok(FileExpertExtent { + role: named, + absolute: tensor.absolute_start, + bytes: tensor.byte_length, + expert_bytes: usize::try_from(length).map_err(|_| BindingError::Range("file_expert_bytes"))?, + kind: tensor.kind, + }) + } + pub fn validate_file_expert_source(&self, lease: &FileExpertSourceLease) -> Result<(), BindingError> { lease.validate_current()?; if self.shards[0].artifact_sha256() != lease.digest() @@ -111,15 +113,12 @@ impl Qwen4ExpArtifact { } // Two dup'd file descriptors of the same actual admitted FD, not pathname identity. let current = self.shards[0].expert_file_owner().map_err(BindingError::Io)?; - #[cfg(unix)] - { - use std::os::unix::fs::MetadataExt; - let a = current.file().metadata().map_err(|e| BindingError::Io(e.into()))?; - let b = lease.file().metadata().map_err(|e| BindingError::Io(e.into()))?; - if a.dev() != b.dev() || a.ino() != b.ino() { - return Err(BindingError::Identity(0)); - } - } + check_same_file(¤t, lease)?; + self.check_lease_members(lease) + } + + /// Every member of the lease still describes the tensor of its role. + fn check_lease_members(&self, lease: &FileExpertSourceLease) -> Result<(), BindingError> { for member in &lease.members { let tensor = self.roles.get(&member.role).ok_or(BindingError::Role("file_expert_role"))?; if tensor.absolute_start != member.absolute @@ -132,3 +131,30 @@ impl Qwen4ExpArtifact { Ok(()) } } + +/// The bytes of one expert of the bank: the 512 experts are equal spans that fill the tensor from its start. +fn expert_stride(tensor: &ResolvedTensor, named: TensorRole, role: LayerRole) -> Result { + let rows = if role == LayerRole::FfnDownExperts { 2560 } else { 640 }; + let (offset, length) = plan_stream_rows(tensor, named, 0, rows, Some(0))?; + if offset != 0 || length.checked_mul(512) != Some(tensor.byte_length) { + return Err(BindingError::Geometry("file_expert_bank")); + } + Ok(length) +} + +/// The current owner and the lease name the same device and inode. +#[cfg(unix)] +fn check_same_file(current: &gguf::ExpertFileOwner, lease: &FileExpertSourceLease) -> Result<(), BindingError> { + use std::os::unix::fs::MetadataExt; + let a = current.file().metadata().map_err(|e| BindingError::Io(e.into()))?; + let b = lease.file().metadata().map_err(|e| BindingError::Io(e.into()))?; + if a.dev() != b.dev() || a.ino() != b.ino() { + return Err(BindingError::Identity(0)); + } + Ok(()) +} + +#[cfg(not(unix))] +fn check_same_file(_current: &gguf::ExpertFileOwner, _lease: &FileExpertSourceLease) -> Result<(), BindingError> { + Ok(()) +} diff --git a/crates/model-format/src/readahead.rs b/crates/model-format/src/readahead.rs index 5716480f..6be80f28 100644 --- a/crates/model-format/src/readahead.rs +++ b/crates/model-format/src/readahead.rs @@ -87,7 +87,8 @@ fn advise_sequential(file: &File) { #[cfg(not(target_os = "linux"))] fn advise_sequential(_file: &File) {} -/// How far ahead of the reader the kernel is asked to fetch (`POSIX_FADV_WILLNEED`). A cold NVMe that serves one 128 KiB +/// How far ahead of the reader the kernel is asked to fetch (`POSIX_FADV_WILLNEED`). A cold NVMe that serves one 128 +/// KiB /// window at a time reads at tens of MB/s; a few hundred MB of asynchronous readahead keeps its queue full while the /// hash runs. #[cfg(target_os = "linux")] @@ -103,9 +104,12 @@ fn advise_willneed(file: &File, offset: u64, len: u64) { #[cfg(not(target_os = "linux"))] fn advise_willneed(_file: &File, _offset: u64, _len: u64) {} -/// Drop the clean page-cache pages of a span that has been read and handed on (`POSIX_FADV_DONTNEED`, never `drop_caches`; -/// best effort, a no-op for a memfd). A hash pass reads each byte once: without this the 55 GB archive and the 84 GB of shards -/// would sit in the page cache after the pass as a second copy of what the process keeps (or does not need) in its own memory. +/// Drop the clean page-cache pages of a span that has been read and handed on (`POSIX_FADV_DONTNEED`, never +/// `drop_caches`; +/// best effort, a no-op for a memfd). A hash pass reads each byte once: without this the 55 GB archive and the 84 GB of +/// shards +/// would sit in the page cache after the pass as a second copy of what the process keeps (or does not need) in its own +/// memory. #[cfg(target_os = "linux")] fn evict_span(file: &File, offset: u64, len: u64) { if let Some(len) = std::num::NonZeroU64::new(len) { @@ -136,46 +140,56 @@ pub(crate) fn with_read_ahead( } advise_sequential(file); thread::scope(|scope| { - scope.spawn(move || { - let mut offset = 0u64; - let mut advised = start; - while offset < bytes { - let count = (bytes - offset).min(CHUNK_BYTES as u64) as usize; - #[cfg(target_os = "linux")] - { - let target = (start + offset + count as u64 + WILLNEED_AHEAD).min(start + bytes); - if target > advised { - advise_willneed(file, advised, target - advised); - advised = target; - } - } - #[cfg(not(target_os = "linux"))] - let _ = (&mut advised, advise_willneed as fn(&File, u64, u64)); - let mut buffer = pool.lock().ok().and_then(|mut p| p.pop()).unwrap_or_default(); - buffer.resize(count, 0); - if let Err(error) = read_exact_at(file, &mut buffer, start + offset) { - for tx in &senders { - let _ = tx.send(Err(io::Error::new(error.kind(), error.to_string()))); - } - return; - } - // The bytes are in `buffer` now; the cached pages behind them are not needed again by this pass. - evict_span(file, start + offset, count as u64); - let chunk = Arc::new(Chunk { offset, data: buffer, pool: Arc::clone(&pool) }); - let mut any = false; - for tx in &senders { - any |= tx.send(Ok(Arc::clone(&chunk))).is_ok(); - } - if !any { - return; - } - offset += count as u64; - } - }); + scope.spawn(move || pump(file, (start, bytes), &senders, &pool)); body(receivers) }) } +/// The reader thread: reads the span chunk by chunk and sends every chunk to every consumer, until the span is +/// read, a read fails (the error goes to all consumers) or no consumer is left. +fn pump(file: &File, (start, bytes): (u64, u64), senders: &[SyncSender>>], pool: &Pool) { + let mut offset = 0u64; + let mut advised = start; + while offset < bytes { + let count = (bytes - offset).min(CHUNK_BYTES as u64) as usize; + advise_ahead(file, &mut advised, (start, bytes), offset + count as u64); + let mut buffer = pool.lock().ok().and_then(|mut p| p.pop()).unwrap_or_default(); + buffer.resize(count, 0); + if let Err(error) = read_exact_at(file, &mut buffer, start + offset) { + for tx in senders { + let _ = tx.send(Err(io::Error::new(error.kind(), error.to_string()))); + } + return; + } + // The bytes are in `buffer` now; the cached pages behind them are not needed again by this pass. + evict_span(file, start + offset, count as u64); + let chunk = Arc::new(Chunk { offset, data: buffer, pool: Arc::clone(pool) }); + let mut any = false; + for tx in senders { + any |= tx.send(Ok(Arc::clone(&chunk))).is_ok(); + } + if !any { + return; + } + offset += count as u64; + } +} + +/// Asks the kernel to fetch up to `WILLNEED_AHEAD` bytes beyond `read_end` (an offset in the span), each byte once. +#[cfg(target_os = "linux")] +fn advise_ahead(file: &File, advised: &mut u64, (start, bytes): (u64, u64), read_end: u64) { + let target = (start + read_end + WILLNEED_AHEAD).min(start + bytes); + if target > *advised { + advise_willneed(file, *advised, target - *advised); + *advised = target; + } +} + +#[cfg(not(target_os = "linux"))] +fn advise_ahead(_file: &File, advised: &mut u64, _span: (u64, u64), _read_end: u64) { + let _ = (advised, advise_willneed as fn(&File, u64, u64)); +} + #[cfg(test)] mod tests { use super::*;