diff --git a/.crumb b/.crumb index 7018cf08..8bf031ee 100644 --- a/.crumb +++ b/.crumb @@ -119,14 +119,14 @@ } ], "children_root": "sha256:31b31d0c22430a2b7dbaf536741c122daa8e98b3e30440b78e6f0b153415c048", - "compiled_at": "2026-10-30T00:10:08Z", + "compiled_at": "2026-10-30T03:27:35Z", "compiler": "crumb-compile/1", - "digest": "sha256:b97852c023146eb2939864627f05574ec68033039b1cb459c690af2fb9e3be1e", + "digest": "sha256:c546eec7ef8f8fef9070c73dea09205848a64ea17296ef307deb6292061a0bd3", "evidence_files": 3586, "evidence_root": "sha256:ee29710af304de14c30917f3cc8eb87c5b5e9a42b75dd9d009e842279d8075d0", - "files": 8040, - "generated_at_commit": "402025cdb5f2a4d7e8a7f88242273aa910ad1f05", - "source_tree": "sha256:1e10e73b47b8e731b09b4618f6bda1803d041b95c4c0c0623becefc4f5a7b954" + "files": 8055, + "generated_at_commit": "b20182607e07391024e4e9cacca4868d88390d5a", + "source_tree": "sha256:8f6b80fbe5362465a296d871241c322de5654f35e698f02b35745a3ff9db2ebf" } }, "history": [], diff --git a/Cargo.lock b/Cargo.lock index 988c7521..8ca9b953 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -167,11 +167,23 @@ dependencies = [ "uuid", ] +[[package]] +name = "aien-expert-store" +version = "0.1.0" +dependencies = [ + "libc", + "serde_json", + "sha2 0.10.9", + "subtle", + "zeroize", +] + [[package]] name = "aien-inference-abi" version = "0.1.0" dependencies = [ "aien-abi-core", + "aien-expert-store", "aien-kv-cache", "aien-omega-bf16", "aien-omega-dattn", diff --git a/Cargo.toml b/Cargo.toml index 66c9e3eb..27e37904 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -23,6 +23,7 @@ members = [ "crates/aien-inference-abi", "crates/aien-kv-cache", "crates/aien-kv-store", + "crates/aien-expert-store", "crates/aien-scheduler", "crates/aien-security", "crates/aien-platform", diff --git a/crates/aien-expert-store/Cargo.toml b/crates/aien-expert-store/Cargo.toml new file mode 100644 index 00000000..0ba3740a --- /dev/null +++ b/crates/aien-expert-store/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "aien-expert-store" +version.workspace = true +edition.workspace = true +license.workspace = true +authors.workspace = true +repository.workspace = true +description = "Content-addressed FP8 expert-weight store and bounded verified read adapter (RIBBON P1, sc#629)" + +[dependencies] +sha2 = "0.10" +subtle = "2.6" +zeroize = "1" +# Shard headers and model.safetensors.index.json of the source checkpoint. +serde_json = "1.0" +# O_NOFOLLOW for object opens and O_DIRECT for the direct read mode. +libc = "0.2" diff --git a/crates/aien-expert-store/src/adapter.rs b/crates/aien-expert-store/src/adapter.rs new file mode 100644 index 00000000..2254d734 --- /dev/null +++ b/crates/aien-expert-store/src/adapter.rs @@ -0,0 +1,418 @@ +//! The bounded asynchronous read adapter. +//! +//! Rules, in one place: +//! +//! * `submit` is non-blocking and bounded. It refuses (handing the staging +//! buffer back) when the queue depth (`max_in_flight`), the in-flight byte +//! budget (`max_inflight_bytes`), the object size bound +//! (`max_object_bytes`) or the buffer capacity would be exceeded, when the +//! deadline has already passed, or after shutdown. +//! * Every accepted read yields exactly one terminal [`ReadCompletion`]: +//! `Ready`, `Failed` or `Cancelled`. The staging buffer travels back in it. +//! * A read is `Ready` only after the whole object was read, its SHA-256 +//! compared in constant time with the index digest, and its header matched +//! against the requested key and length. Otherwise the buffer is scrubbed +//! before it is returned; no partial or unverified bytes are ever visible. +//! * Cancellation and the deadline are checked before every chunk and once +//! more before the read is marked ready. A single read call that never +//! returns cannot be preempted; `chunk_bytes` bounds how long one call can +//! delay detection. + +use crate::error::ReadError; +use crate::format::{digest_eq, sha256, ArtifactHeader, IndexEntry, ALIGN, HEADER_REGION}; +use crate::source::BlockSource; +use crate::staging::StagingBuffer; +use std::collections::{HashMap, VecDeque}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::mpsc::{channel, Receiver, Sender}; +use std::sync::{Arc, Condvar, Mutex}; +use std::thread::JoinHandle; +use std::time::{Duration, Instant}; + +/// Explicit bounds of one adapter. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ReadLimits { + /// Queue depth: reads queued or running at once (also the worker count). + pub max_in_flight: usize, + /// Sum of the object lengths of reads queued or running. + pub max_inflight_bytes: u64, + /// Largest object a single read may fetch. + pub max_object_bytes: u64, + /// Bytes per read call; a 4096 multiple so direct reads stay aligned. + pub chunk_bytes: usize, +} + +impl Default for ReadLimits { + fn default() -> Self { + Self { + max_in_flight: 4, + max_inflight_bytes: 256 << 20, + max_object_bytes: 64 << 20, + chunk_bytes: 1 << 20, + } + } +} + +/// Never reused within one adapter. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct Ticket(pub u64); + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum CancelOutcome { + /// The read will end `Cancelled` unless it was already verified. + Requested, + /// No such read is in flight (unknown, or its terminal was already sent). + Unknown, +} + +/// A verified artifact in its staging buffer. +#[derive(Debug)] +pub struct ReadyExpert { + pub header: ArtifactHeader, + pub entry: IndexEntry, + buf: StagingBuffer, +} + +impl ReadyExpert { + /// The FP8 weight bytes, exactly as in the source checkpoint. + pub fn weights(&self) -> &[u8] { + &self.buf.as_slice()[self.header.weight_range()] + } + + /// The scale bytes, exactly as in the source checkpoint. + pub fn scales(&self) -> &[u8] { + &self.buf.as_slice()[self.header.scale_range()] + } + + /// The whole verified artifact. + pub fn artifact(&self) -> &[u8] { + &self.buf.as_slice()[..self.header.object_len as usize] + } + + /// Gives the buffer back for reuse (it still holds the verified bytes). + pub fn into_buffer(self) -> StagingBuffer { + self.buf + } +} + +#[derive(Debug)] +pub enum Outcome { + Ready(ReadyExpert), + /// The buffer has been scrubbed. + Failed { + error: ReadError, + buf: StagingBuffer, + }, + /// The buffer has been scrubbed. + Cancelled { + buf: StagingBuffer, + }, +} + +#[derive(Debug)] +pub struct ReadCompletion { + pub ticket: Ticket, + pub outcome: Outcome, + pub elapsed: Duration, +} + +/// A refused submit: the reason and the caller's buffer, untouched. +#[derive(Debug)] +pub struct Refused { + pub error: ReadError, + pub buf: StagingBuffer, +} + +struct Job { + ticket: Ticket, + entry: IndexEntry, + deadline: Instant, + buf: StagingBuffer, + cancel: Arc, + submitted: Instant, +} + +#[derive(Default)] +struct State { + queue: VecDeque, + in_flight: usize, + in_flight_bytes: u64, + next_ticket: u64, + cancels: HashMap>, + shutdown: bool, +} + +struct Shared { + limits: ReadLimits, + source: Arc, + state: Mutex, + work: Condvar, +} + +pub struct ReadAdapter { + shared: Arc, + workers: Vec>, + completions: Mutex>, +} + +impl ReadAdapter { + /// Starts `limits.max_in_flight` workers over `source`. Limits that are + /// zero, or a `chunk_bytes` that is not a 4096 multiple, are refused. + pub fn new(source: Arc, limits: ReadLimits) -> Result { + if limits.max_in_flight == 0 + || limits.max_inflight_bytes == 0 + || limits.max_object_bytes == 0 + || limits.chunk_bytes == 0 + || !(limits.chunk_bytes as u64).is_multiple_of(ALIGN) + { + return Err(ReadError::InvalidLimits); + } + let shared = Arc::new(Shared { + limits, + source, + state: Mutex::new(State::default()), + work: Condvar::new(), + }); + let (tx, rx) = channel(); + let workers = (0..limits.max_in_flight) + .map(|_| { + let shared = Arc::clone(&shared); + let tx: Sender = tx.clone(); + std::thread::spawn(move || worker(shared, tx)) + }) + .collect(); + Ok(Self { + shared, + workers, + completions: Mutex::new(rx), + }) + } + + pub fn limits(&self) -> ReadLimits { + self.shared.limits + } + + /// Reads queued or running, and their bytes. + pub fn in_flight(&self) -> (usize, u64) { + let st = self.shared.state.lock().unwrap(); + (st.in_flight, st.in_flight_bytes) + } + + /// Queues one verified read of `entry` into `buf`. Non-blocking. + pub fn submit( + &self, + entry: IndexEntry, + buf: StagingBuffer, + deadline: Instant, + ) -> Result { + let l = &self.shared.limits; + let refuse = |error, buf| Err(Refused { error, buf }); + let len = entry.object_len; + if len <= HEADER_REGION as u64 || !len.is_multiple_of(ALIGN) { + return refuse(ReadError::InvalidEntry, buf); + } + if len > l.max_object_bytes { + return refuse(ReadError::ObjectTooLarge, buf); + } + if len > buf.capacity() as u64 { + return refuse( + ReadError::InsufficientCapacity { + need: len, + have: buf.capacity() as u64, + }, + buf, + ); + } + let now = Instant::now(); + if deadline <= now { + return refuse(ReadError::DeadlineExceeded, buf); + } + let mut st = self.shared.state.lock().unwrap(); + if st.shutdown { + return refuse(ReadError::ShutDown, buf); + } + if st.in_flight >= l.max_in_flight { + return refuse(ReadError::QueueFull, buf); + } + if st.in_flight_bytes.saturating_add(len) > l.max_inflight_bytes { + return refuse(ReadError::InflightBytesExceeded, buf); + } + let ticket = Ticket(st.next_ticket); + st.next_ticket += 1; + st.in_flight += 1; + st.in_flight_bytes += len; + let cancel = Arc::new(AtomicBool::new(false)); + st.cancels.insert(ticket.0, Arc::clone(&cancel)); + st.queue.push_back(Job { + ticket, + entry, + deadline, + buf, + cancel, + submitted: now, + }); + drop(st); + self.shared.work.notify_one(); + Ok(ticket) + } + + /// Requests cancellation. Returns immediately; the read still yields its + /// one terminal completion. + pub fn cancel(&self, ticket: Ticket) -> CancelOutcome { + let st = self.shared.state.lock().unwrap(); + match st.cancels.get(&ticket.0) { + Some(flag) => { + flag.store(true, Ordering::SeqCst); + CancelOutcome::Requested + } + None => CancelOutcome::Unknown, + } + } + + /// Non-blocking: at most `max` completions, oldest first. + pub fn poll(&self, max: usize) -> Vec { + let rx = self.completions.lock().unwrap(); + let mut out = Vec::new(); + while out.len() < max { + match rx.try_recv() { + Ok(c) => out.push(c), + Err(_) => break, + } + } + out + } + + /// Blocks up to `timeout` for the next completion. + pub fn wait(&self, timeout: Duration) -> Option { + let rx = self.completions.lock().unwrap(); + rx.recv_timeout(timeout).ok() + } +} + +impl Drop for ReadAdapter { + /// Stops intake, cancels every queued and running read and joins the workers. + fn drop(&mut self) { + { + let mut st = self.shared.state.lock().unwrap(); + st.shutdown = true; + for flag in st.cancels.values() { + flag.store(true, Ordering::SeqCst); + } + } + self.shared.work.notify_all(); + for w in self.workers.drain(..) { + let _ = w.join(); + } + } +} + +fn worker(shared: Arc, tx: Sender) { + loop { + let job = { + let mut st = shared.state.lock().unwrap(); + loop { + if let Some(job) = st.queue.pop_front() { + break job; + } + if st.shutdown { + return; + } + st = shared.work.wait(st).unwrap(); + } + }; + let ticket = job.ticket; + let len = job.entry.object_len; + let submitted = job.submitted; + let outcome = run(&shared, job); + { + let mut st = shared.state.lock().unwrap(); + st.in_flight -= 1; + st.in_flight_bytes -= len; + st.cancels.remove(&ticket.0); + } + // A dropped receiver only means nobody is listening any more. + let _ = tx.send(ReadCompletion { + ticket, + outcome, + elapsed: submitted.elapsed(), + }); + } +} + +enum Stop { + Error(ReadError), + Cancelled, +} + +fn run(shared: &Shared, job: Job) -> Outcome { + let Job { + entry, + deadline, + mut buf, + cancel, + .. + } = job; + match fill_and_verify(shared, &entry, deadline, &cancel, &mut buf) { + Ok(header) => Outcome::Ready(ReadyExpert { header, entry, buf }), + Err(stop) => { + buf.scrub(); + match stop { + Stop::Cancelled => Outcome::Cancelled { buf }, + Stop::Error(error) => Outcome::Failed { error, buf }, + } + } + } +} + +fn checkpoint(deadline: Instant, cancel: &AtomicBool) -> Result<(), Stop> { + if cancel.load(Ordering::SeqCst) { + return Err(Stop::Cancelled); + } + if Instant::now() >= deadline { + return Err(Stop::Error(ReadError::DeadlineExceeded)); + } + Ok(()) +} + +fn fill_and_verify( + shared: &Shared, + entry: &IndexEntry, + deadline: Instant, + cancel: &AtomicBool, + buf: &mut StagingBuffer, +) -> Result { + let e = Stop::Error; + checkpoint(deadline, cancel)?; + let expected = entry.object_len; + let mut reader = shared.source.open(&entry.data_digest).map_err(e)?; + let found = reader.size().map_err(e)?; + if found != expected { + return Err(e(ReadError::LengthMismatch { expected, found })); + } + let n = expected as usize; + let dst = &mut buf.as_mut_slice()[..n]; + let mut done = 0usize; + while done < n { + checkpoint(deadline, cancel)?; + let end = (done + shared.limits.chunk_bytes).min(n); + let got = reader + .read_at(done as u64, &mut dst[done..end]) + .map_err(e)?; + if got == 0 { + return Err(e(ReadError::UnexpectedEof { + read: done as u64, + expected, + })); + } + done += got.min(end - done); + } + if !digest_eq(&sha256(dst), &entry.data_digest) { + return Err(e(ReadError::DigestMismatch)); + } + let header = ArtifactHeader::decode(dst).map_err(|_| e(ReadError::HeaderMismatch))?; + if header.key != entry.key || header.object_len != expected { + return Err(e(ReadError::HeaderMismatch)); + } + checkpoint(deadline, cancel)?; + Ok(header) +} diff --git a/crates/aien-expert-store/src/error.rs b/crates/aien-expert-store/src/error.rs new file mode 100644 index 00000000..c142ab64 --- /dev/null +++ b/crates/aien-expert-store/src/error.rs @@ -0,0 +1,122 @@ +//! Structured errors. [`StoreError`] covers the store, the formats and the +//! indexer; [`ReadError`] covers the read adapter and is a plain value. + +use crate::format::ExpertKey; +use std::io::ErrorKind; + +/// Why a store, index, artifact or checkpoint operation was refused. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum StoreError { + /// An I/O call failed (the kind only, no path, so nothing private leaks). + Io(ErrorKind), + BadMagic, + UnsupportedVersion, + /// An artifact header field is out of range or disagrees with the others. + BadHeader(&'static str), + /// The index file is malformed (size, ordering, reserved bytes, enums). + BadIndex(&'static str), + /// The index trailer digest does not match its contents. + IndexChecksum, + /// A key is already bound to different content. + DuplicateKey(ExpertKey), + /// Weight or scale bytes do not have the length the geometry requires. + PayloadLength { + expected: u64, + found: u64, + }, + /// More entries than `StoreLimits::max_entries`. + TooManyEntries, + /// An artifact larger than `StoreLimits::max_object_bytes`. + ObjectTooLarge { + len: u64, + max: u64, + }, + /// An existing object file does not hash to its name. + ObjectCorrupt, + /// A size computation overflowed. + Overflow, + /// The store root would be inside the source checkpoint directory. + StoreInsideCheckpoint, + /// The checkpoint index or a shard header is malformed. + Checkpoint(String), + /// A tensor the index or the expert layout requires is missing. + MissingTensor(String), + /// A tensor has the wrong dtype. + DtypeMismatch { + name: String, + found: String, + }, + /// A tensor has the wrong shape. + ShapeMismatch { + name: String, + }, +} + +impl From for StoreError { + fn from(e: std::io::Error) -> Self { + Self::Io(e.kind()) + } +} + +impl core::fmt::Display for StoreError { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + write!(f, "expert store: {self:?}") + } +} + +impl std::error::Error for StoreError {} + +/// Why a read was refused at submit or failed before it became ready. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ReadError { + /// `max_in_flight` jobs are already queued or running. + QueueFull, + /// Admitting this read would exceed `max_inflight_bytes`. + InflightBytesExceeded, + /// The object is larger than `max_object_bytes`. + ObjectTooLarge, + /// The staging buffer is smaller than the object. + InsufficientCapacity { need: u64, have: u64 }, + /// The index entry cannot describe a valid artifact (length not aligned or + /// smaller than the header region). + InvalidEntry, + /// The deadline passed before submit, or before the read finished. + DeadlineExceeded, + /// The adapter is shutting down. + ShutDown, + /// No object with that digest exists in the source. + NotFound, + /// An I/O call failed. + Io(ErrorKind), + /// The object has a different length than the index records (truncated or + /// extended file). + LengthMismatch { expected: u64, found: u64 }, + /// The source returned end of file before the object was complete. + UnexpectedEof { read: u64, expected: u64 }, + /// SHA-256 of the bytes read differs from the index digest. + DigestMismatch, + /// The bytes hash correctly but their header does not describe the + /// requested key and length. + HeaderMismatch, + /// Adapter limits that are zero, or a chunk size that is not a 4096 multiple. + InvalidLimits, + /// Direct I/O is not available on this platform or file system. + DirectIoUnsupported, +} + +impl From for ReadError { + fn from(e: std::io::Error) -> Self { + match e.kind() { + ErrorKind::NotFound => Self::NotFound, + k => Self::Io(k), + } + } +} + +impl core::fmt::Display for ReadError { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + write!(f, "expert read: {self:?}") + } +} + +impl std::error::Error for ReadError {} diff --git a/crates/aien-expert-store/src/fake.rs b/crates/aien-expert-store/src/fake.rs new file mode 100644 index 00000000..fcbe06d0 --- /dev/null +++ b/crates/aien-expert-store/src/fake.rs @@ -0,0 +1,167 @@ +//! A tiny deterministic in-memory [`BlockSource`] with injectable faults, for +//! concurrency, latency, failure, corruption and cancellation tests. No +//! randomness, no device access. + +use crate::error::ReadError; +use crate::source::{BlockReader, BlockSource}; +use std::collections::HashMap; +use std::io::ErrorKind; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, Condvar, Mutex}; +use std::time::Duration; + +/// A fault applied to every read of one object. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Fault { + /// XOR 0x01 into the byte at this offset as it is read. + CorruptByte(u64), + /// The object is this many bytes long (length and data both shortened). + Truncate(u64), + /// `len` reports the full length but reads return end of file from this offset. + EofAt(u64), + /// Each read returns at most this many bytes. + ShortReads(usize), + /// Every read fails with this error kind. + IoError(ErrorKind), + /// Each read sleeps this long first (a slow or stalled device). + Delay(Duration), +} + +#[derive(Default)] +struct State { + objects: HashMap<[u8; 32], Arc>>, + faults: HashMap<[u8; 32], Fault>, + held: bool, +} + +#[derive(Default)] +struct Inner { + state: Mutex, + gate: Condvar, + active: AtomicUsize, + peak: AtomicUsize, + reads: AtomicUsize, +} + +/// Cloning shares the same objects, faults and counters. +#[derive(Clone, Default)] +pub struct FakeSource(Arc); + +impl FakeSource { + pub fn new() -> Self { + Self::default() + } + + pub fn insert(&self, digest: [u8; 32], bytes: Vec) { + self.0 + .state + .lock() + .unwrap() + .objects + .insert(digest, Arc::new(bytes)); + } + + pub fn set_fault(&self, digest: [u8; 32], fault: Fault) { + self.0.state.lock().unwrap().faults.insert(digest, fault); + } + + pub fn clear_fault(&self, digest: &[u8; 32]) { + self.0.state.lock().unwrap().faults.remove(digest); + } + + /// Blocks every read at entry until [`FakeSource::release`]. + pub fn hold(&self) { + self.0.state.lock().unwrap().held = true; + } + + pub fn release(&self) { + self.0.state.lock().unwrap().held = false; + self.0.gate.notify_all(); + } + + /// Reads currently inside `read_at`. + pub fn active(&self) -> usize { + self.0.active.load(Ordering::SeqCst) + } + + /// Most reads ever inside `read_at` at once. + pub fn peak(&self) -> usize { + self.0.peak.load(Ordering::SeqCst) + } + + /// Total `read_at` calls. + pub fn reads(&self) -> usize { + self.0.reads.load(Ordering::SeqCst) + } +} + +struct FakeReader { + inner: Arc, + bytes: Arc>, + fault: Option, +} + +struct ActiveGuard<'a>(&'a Inner); + +impl Drop for ActiveGuard<'_> { + fn drop(&mut self) { + self.0.active.fetch_sub(1, Ordering::SeqCst); + } +} + +impl BlockReader for FakeReader { + fn size(&self) -> Result { + let full = self.bytes.len() as u64; + Ok(match self.fault { + Some(Fault::Truncate(n)) => n.min(full), + _ => full, + }) + } + + fn read_at(&mut self, offset: u64, dst: &mut [u8]) -> Result { + self.inner.reads.fetch_add(1, Ordering::SeqCst); + let now = self.inner.active.fetch_add(1, Ordering::SeqCst) + 1; + self.inner.peak.fetch_max(now, Ordering::SeqCst); + let _active = ActiveGuard(&self.inner); + { + let mut st = self.inner.state.lock().unwrap(); + while st.held { + st = self.inner.gate.wait(st).unwrap(); + } + } + let mut end = self.bytes.len() as u64; + let mut max = dst.len(); + match self.fault { + Some(Fault::IoError(k)) => return Err(ReadError::Io(k)), + Some(Fault::Delay(d)) => std::thread::sleep(d), + Some(Fault::Truncate(n)) | Some(Fault::EofAt(n)) => end = end.min(n), + Some(Fault::ShortReads(n)) => max = max.min(n.max(1)), + Some(Fault::CorruptByte(_)) | None => {} + } + if offset >= end { + return Ok(0); + } + let n = ((end - offset) as usize).min(max); + let start = offset as usize; + dst[..n].copy_from_slice(&self.bytes[start..start + n]); + if let Some(Fault::CorruptByte(at)) = self.fault { + if at >= offset && at < offset + n as u64 { + dst[(at - offset) as usize] ^= 0x01; + } + } + Ok(n) + } +} + +impl BlockSource for FakeSource { + fn open(&self, digest: &[u8; 32]) -> Result, ReadError> { + let st = self.0.state.lock().unwrap(); + let bytes = st.objects.get(digest).cloned().ok_or(ReadError::NotFound)?; + let fault = st.faults.get(digest).copied(); + Ok(Box::new(FakeReader { + inner: Arc::clone(&self.0), + bytes, + fault, + })) + } +} diff --git a/crates/aien-expert-store/src/format.rs b/crates/aien-expert-store/src/format.rs new file mode 100644 index 00000000..130cfb33 --- /dev/null +++ b/crates/aien-expert-store/src/format.rs @@ -0,0 +1,471 @@ +//! Canonical byte formats: the expert artifact and the versioned index. +//! +//! Artifact (all integers little endian): +//! +//! ```text +//! 0..4096 header region (fields below, every other byte zero) +//! 4096..4096+W FP8 E4M3 weight bytes, row major [rows][cols], as in the checkpoint +//! S..S+L scale bytes [ceil(rows/128)][ceil(cols/128)], as in the checkpoint +//! (S = round_up(4096 + W, 4096)) +//! S+L..object_len zero padding to a 4096 multiple +//! ``` +//! +//! Header fields: magic `AIENXPRT` (0..8), version (8..12), header_len 4096 +//! (12..16), model digest (16..48), layer (48..52), expert (52..56), +//! projection (56), quantization (57), weight dtype (58, 1 = F8_E4M3), scale +//! dtype (59), block (60..64), rows (64..72), cols (72..80), scale rows +//! (80..88), scale cols (88..96), weight offset (96..104), weight length +//! (104..112), scale offset (112..120), scale length (120..128), object length +//! (128..136). +//! +//! The content address is SHA-256 of the whole artifact. Because the digest +//! covers the header, the payload and the padding, it binds the weight bytes +//! themselves, not only an index of them (sc#338). +//! +//! Index: magic `AIENXIDX` (0..8), version (8..12), entry length 84 (12..16), +//! entry count (16..24), the entries in strictly ascending key order (so a +//! duplicate key is a format error), then SHA-256 of everything before it. + +use crate::error::StoreError; +use sha2::{Digest, Sha256}; +use subtle::ConstantTimeEq; + +pub const OBJECT_MAGIC: [u8; 8] = *b"AIENXPRT"; +pub const INDEX_MAGIC: [u8; 8] = *b"AIENXIDX"; +pub const FORMAT_VERSION: u32 = 1; +/// Size of the artifact header region; the weight bytes start here. +pub const HEADER_REGION: usize = 4096; +/// Alignment of every payload offset and of the artifact length (direct I/O). +pub const ALIGN: u64 = 4096; +/// FP8 quantization block edge (rows and columns). +pub const FP8_BLOCK: u64 = 128; +/// Bytes of one index entry. +pub const INDEX_ENTRY_LEN: usize = 84; +const INDEX_PREFIX_LEN: usize = 24; +const HEADER_FIELDS_END: usize = 136; +const WEIGHT_DTYPE_F8_E4M3: u8 = 1; + +/// Which projection of an expert's MLP. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +#[repr(u8)] +pub enum Projection { + Gate = 1, + Up = 2, + Down = 3, +} + +impl Projection { + pub const ALL: [Projection; 3] = [Projection::Gate, Projection::Up, Projection::Down]; + + pub fn from_u8(v: u8) -> Option { + match v { + 1 => Some(Self::Gate), + 2 => Some(Self::Up), + 3 => Some(Self::Down), + _ => None, + } + } + + /// The checkpoint tensor name component (`gate_proj`, `up_proj`, `down_proj`). + pub fn checkpoint_name(self) -> &'static str { + match self { + Self::Gate => "gate_proj", + Self::Up => "up_proj", + Self::Down => "down_proj", + } + } +} + +/// Quantization format of the weight bytes. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +#[repr(u8)] +pub enum QuantFormat { + /// FP8 E4M3 weights with one scale per 128 x 128 block. + Fp8E4m3Block128 = 1, +} + +impl QuantFormat { + pub fn from_u8(v: u8) -> Option { + match v { + 1 => Some(Self::Fp8E4m3Block128), + _ => None, + } + } +} + +/// Element type of the stored scale bytes (kept exactly as the checkpoint has them). +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +#[repr(u8)] +pub enum ScaleDtype { + Bf16 = 1, + F32 = 2, +} + +impl ScaleDtype { + pub fn from_u8(v: u8) -> Option { + match v { + 1 => Some(Self::Bf16), + 2 => Some(Self::F32), + _ => None, + } + } + + pub fn from_safetensors(s: &str) -> Option { + match s { + "BF16" => Some(Self::Bf16), + "F32" => Some(Self::F32), + _ => None, + } + } + + pub fn safetensors_name(self) -> &'static str { + match self { + Self::Bf16 => "BF16", + Self::F32 => "F32", + } + } + + pub fn size(self) -> u64 { + match self { + Self::Bf16 => 2, + Self::F32 => 4, + } + } +} + +/// The identity of one stored tensor pair. Ordered field by field, in +/// declaration order (the index order). +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct ExpertKey { + pub model_digest: [u8; 32], + pub layer: u32, + pub expert: u32, + pub projection: Projection, + pub quant: QuantFormat, +} + +/// One index record: the key, the content address and the artifact length. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct IndexEntry { + pub key: ExpertKey, + pub data_digest: [u8; 32], + pub object_len: u64, +} + +/// The decoded artifact header. Every field after `scale_dtype` is derived +/// from `(rows, cols, scale_dtype)`; `decode` recomputes and compares them. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ArtifactHeader { + pub key: ExpertKey, + pub rows: u64, + pub cols: u64, + pub scale_dtype: ScaleDtype, + pub scale_rows: u64, + pub scale_cols: u64, + pub weight_offset: u64, + pub weight_len: u64, + pub scale_offset: u64, + pub scale_len: u64, + pub object_len: u64, +} + +fn round_up(v: u64, align: u64) -> Option { + v.checked_add(align - 1).map(|x| x / align * align) +} + +fn rd_u32(b: &[u8], at: usize) -> u32 { + let mut a = [0u8; 4]; + a.copy_from_slice(&b[at..at + 4]); + u32::from_le_bytes(a) +} + +fn rd_u64(b: &[u8], at: usize) -> u64 { + let mut a = [0u8; 8]; + a.copy_from_slice(&b[at..at + 8]); + u64::from_le_bytes(a) +} + +impl ArtifactHeader { + /// The canonical layout for a `[rows][cols]` FP8 weight with block-128 scales. + pub fn new( + key: ExpertKey, + rows: u64, + cols: u64, + scale_dtype: ScaleDtype, + ) -> Result { + if rows == 0 || cols == 0 { + return Err(StoreError::BadHeader("zero rows or cols")); + } + let ov = StoreError::Overflow; + let weight_len = rows.checked_mul(cols).ok_or(ov.clone())?; + let scale_rows = rows.div_ceil(FP8_BLOCK); + let scale_cols = cols.div_ceil(FP8_BLOCK); + let scale_len = scale_rows + .checked_mul(scale_cols) + .and_then(|n| n.checked_mul(scale_dtype.size())) + .ok_or(ov.clone())?; + let weight_offset = HEADER_REGION as u64; + let scale_offset = weight_offset + .checked_add(weight_len) + .and_then(|e| round_up(e, ALIGN)) + .ok_or(ov.clone())?; + let object_len = scale_offset + .checked_add(scale_len) + .and_then(|e| round_up(e, ALIGN)) + .ok_or(ov)?; + Ok(Self { + key, + rows, + cols, + scale_dtype, + scale_rows, + scale_cols, + weight_offset, + weight_len, + scale_offset, + scale_len, + object_len, + }) + } + + /// The 4096-byte canonical header region. + pub fn encode(&self) -> Vec { + let mut h = vec![0u8; HEADER_REGION]; + h[0..8].copy_from_slice(&OBJECT_MAGIC); + h[8..12].copy_from_slice(&FORMAT_VERSION.to_le_bytes()); + h[12..16].copy_from_slice(&(HEADER_REGION as u32).to_le_bytes()); + h[16..48].copy_from_slice(&self.key.model_digest); + h[48..52].copy_from_slice(&self.key.layer.to_le_bytes()); + h[52..56].copy_from_slice(&self.key.expert.to_le_bytes()); + h[56] = self.key.projection as u8; + h[57] = self.key.quant as u8; + h[58] = WEIGHT_DTYPE_F8_E4M3; + h[59] = self.scale_dtype as u8; + h[60..64].copy_from_slice(&(FP8_BLOCK as u32).to_le_bytes()); + let fields = [ + self.rows, + self.cols, + self.scale_rows, + self.scale_cols, + self.weight_offset, + self.weight_len, + self.scale_offset, + self.scale_len, + self.object_len, + ]; + for (i, v) in fields.iter().enumerate() { + let at = 64 + i * 8; + h[at..at + 8].copy_from_slice(&v.to_le_bytes()); + } + h + } + + /// Parses and fully re-derives a header region; any disagreement is refused. + pub fn decode(region: &[u8]) -> Result { + if region.len() < HEADER_REGION { + return Err(StoreError::BadHeader("short header region")); + } + let h = ®ion[..HEADER_REGION]; + if h[0..8] != OBJECT_MAGIC { + return Err(StoreError::BadMagic); + } + if rd_u32(h, 8) != FORMAT_VERSION { + return Err(StoreError::UnsupportedVersion); + } + if rd_u32(h, 12) != HEADER_REGION as u32 { + return Err(StoreError::BadHeader("header_len")); + } + let projection = Projection::from_u8(h[56]).ok_or(StoreError::BadHeader("projection"))?; + let quant = QuantFormat::from_u8(h[57]).ok_or(StoreError::BadHeader("quant"))?; + if h[58] != WEIGHT_DTYPE_F8_E4M3 { + return Err(StoreError::BadHeader("weight dtype")); + } + let scale_dtype = ScaleDtype::from_u8(h[59]).ok_or(StoreError::BadHeader("scale dtype"))?; + if u64::from(rd_u32(h, 60)) != FP8_BLOCK { + return Err(StoreError::BadHeader("block")); + } + if h[HEADER_FIELDS_END..].iter().any(|&b| b != 0) { + return Err(StoreError::BadHeader("nonzero reserved bytes")); + } + let mut model_digest = [0u8; 32]; + model_digest.copy_from_slice(&h[16..48]); + let key = ExpertKey { + model_digest, + layer: rd_u32(h, 48), + expert: rd_u32(h, 52), + projection, + quant, + }; + let want = Self::new(key, rd_u64(h, 64), rd_u64(h, 72), scale_dtype)?; + if want.encode() != h { + return Err(StoreError::BadHeader("derived fields disagree")); + } + Ok(want) + } + + /// The weight byte range inside the artifact. + pub fn weight_range(&self) -> core::ops::Range { + self.weight_offset as usize..(self.weight_offset + self.weight_len) as usize + } + + /// The scale byte range inside the artifact. + pub fn scale_range(&self) -> core::ops::Range { + self.scale_offset as usize..(self.scale_offset + self.scale_len) as usize + } +} + +/// SHA-256 of `bytes`. +pub fn sha256(bytes: &[u8]) -> [u8; 32] { + Sha256::digest(bytes).into() +} + +/// Constant-time equality of two digests. +pub fn digest_eq(a: &[u8; 32], b: &[u8; 32]) -> bool { + a.ct_eq(b).into() +} + +/// Builds the canonical artifact bytes for one projection. `weights` and +/// `scales` are copied verbatim (checkpoint byte order is preserved). +pub fn build_artifact( + key: ExpertKey, + rows: u64, + cols: u64, + scale_dtype: ScaleDtype, + weights: &[u8], + scales: &[u8], + max_object_bytes: u64, +) -> Result<(ArtifactHeader, Vec), StoreError> { + let hdr = ArtifactHeader::new(key, rows, cols, scale_dtype)?; + if weights.len() as u64 != hdr.weight_len { + return Err(StoreError::PayloadLength { + expected: hdr.weight_len, + found: weights.len() as u64, + }); + } + if scales.len() as u64 != hdr.scale_len { + return Err(StoreError::PayloadLength { + expected: hdr.scale_len, + found: scales.len() as u64, + }); + } + if hdr.object_len > max_object_bytes { + return Err(StoreError::ObjectTooLarge { + len: hdr.object_len, + max: max_object_bytes, + }); + } + let len = usize::try_from(hdr.object_len).map_err(|_| StoreError::Overflow)?; + let mut bytes = vec![0u8; len]; + bytes[..HEADER_REGION].copy_from_slice(&hdr.encode()); + bytes[hdr.weight_range()].copy_from_slice(weights); + bytes[hdr.scale_range()].copy_from_slice(scales); + Ok((hdr, bytes)) +} + +/// Encodes an index. Entries must be in strictly ascending key order. +pub fn encode_index(entries: &[IndexEntry]) -> Result, StoreError> { + if entries.windows(2).any(|w| w[0].key >= w[1].key) { + return Err(StoreError::BadIndex("entries not strictly ascending")); + } + let mut out = Vec::with_capacity(INDEX_PREFIX_LEN + entries.len() * INDEX_ENTRY_LEN + 32); + out.extend_from_slice(&INDEX_MAGIC); + out.extend_from_slice(&FORMAT_VERSION.to_le_bytes()); + out.extend_from_slice(&(INDEX_ENTRY_LEN as u32).to_le_bytes()); + out.extend_from_slice(&(entries.len() as u64).to_le_bytes()); + for e in entries { + out.extend_from_slice(&e.key.model_digest); + out.extend_from_slice(&e.key.layer.to_le_bytes()); + out.extend_from_slice(&e.key.expert.to_le_bytes()); + out.push(e.key.projection as u8); + out.push(e.key.quant as u8); + out.extend_from_slice(&[0, 0]); + out.extend_from_slice(&e.data_digest); + out.extend_from_slice(&e.object_len.to_le_bytes()); + } + let trailer = sha256(&out); + out.extend_from_slice(&trailer); + Ok(out) +} + +/// The largest index file `decode_index` accepts for `max_entries`. +pub fn max_index_bytes(max_entries: usize) -> u64 { + (INDEX_PREFIX_LEN + 32) as u64 + max_entries as u64 * INDEX_ENTRY_LEN as u64 +} + +/// Decodes and validates an index: size, trailer (constant time), version, +/// strict key order (no duplicates), reserved bytes, enums and object lengths. +pub fn decode_index(bytes: &[u8], max_entries: usize) -> Result, StoreError> { + if bytes.len() < INDEX_PREFIX_LEN + 32 { + return Err(StoreError::BadIndex("short index")); + } + if bytes[0..8] != INDEX_MAGIC { + return Err(StoreError::BadMagic); + } + let (body, trailer) = bytes.split_at(bytes.len() - 32); + let mut t = [0u8; 32]; + t.copy_from_slice(trailer); + if !digest_eq(&sha256(body), &t) { + return Err(StoreError::IndexChecksum); + } + if rd_u32(body, 8) != FORMAT_VERSION { + return Err(StoreError::UnsupportedVersion); + } + if rd_u32(body, 12) as usize != INDEX_ENTRY_LEN { + return Err(StoreError::BadIndex("entry length")); + } + let count = rd_u64(body, 16); + if count > max_entries as u64 { + return Err(StoreError::TooManyEntries); + } + let records = &body[INDEX_PREFIX_LEN..]; + if records.len() as u64 != count * INDEX_ENTRY_LEN as u64 { + return Err(StoreError::BadIndex("size disagrees with count")); + } + let mut out: Vec = Vec::with_capacity(count as usize); + let (chunks, rest) = records.as_chunks::(); + debug_assert!(rest.is_empty()); + for r in chunks { + let mut model_digest = [0u8; 32]; + model_digest.copy_from_slice(&r[0..32]); + let projection = Projection::from_u8(r[40]).ok_or(StoreError::BadIndex("projection"))?; + let quant = QuantFormat::from_u8(r[41]).ok_or(StoreError::BadIndex("quant"))?; + if r[42] != 0 || r[43] != 0 { + return Err(StoreError::BadIndex("nonzero reserved bytes")); + } + let mut data_digest = [0u8; 32]; + data_digest.copy_from_slice(&r[44..76]); + let object_len = rd_u64(r, 76); + if object_len <= HEADER_REGION as u64 || !object_len.is_multiple_of(ALIGN) { + return Err(StoreError::BadIndex("object length")); + } + let e = IndexEntry { + key: ExpertKey { + model_digest, + layer: rd_u32(r, 32), + expert: rd_u32(r, 36), + projection, + quant, + }, + data_digest, + object_len, + }; + if let Some(prev) = out.last() { + if prev.key >= e.key { + return Err(StoreError::BadIndex("entries not strictly ascending")); + } + } + out.push(e); + } + Ok(out) +} + +/// Lowercase hex of a digest (the object file name). +pub fn hex(d: &[u8; 32]) -> String { + const H: &[u8; 16] = b"0123456789abcdef"; + let mut s = String::with_capacity(64); + for b in d { + s.push(H[(b >> 4) as usize] as char); + s.push(H[(b & 15) as usize] as char); + } + s +} diff --git a/crates/aien-expert-store/src/indexer.rs b/crates/aien-expert-store/src/indexer.rs new file mode 100644 index 00000000..812b3ad1 --- /dev/null +++ b/crates/aien-expert-store/src/indexer.rs @@ -0,0 +1,313 @@ +//! Deterministic, read-only checkpoint-to-artifact indexer. +//! +//! The source checkpoint (`model.safetensors.index.json` plus its shards) is +//! opened read-only and only the tensors of the requested experts are read, +//! through their header byte ranges, so one expert can be fetched without +//! scanning or decoding the other shards. The weight and scale bytes are +//! copied unchanged into artifacts (reversible: `ReadyExpert::weights` and +//! `scales` return exactly the checkpoint bytes). The same checkpoint and +//! arguments always produce the same artifacts, digests and index. +//! +//! The shard checks mirror the resident loader's reader +//! (`aien-inference-abi` `qwen3_moe::Shard`): plain shard file names only, +//! bounded header length, exact dtype, shape and byte range per tensor. + +use crate::error::StoreError; +use crate::format::{ExpertKey, IndexEntry, Projection, QuantFormat, ScaleDtype, FP8_BLOCK}; +use crate::store::ExpertStore; +use std::collections::HashMap; +use std::fs::File; +use std::io::Read; +use std::os::unix::fs::FileExt; +use std::path::{Component, Path, PathBuf}; + +/// Same bound as the resident loader. +const MAX_HEADER_BYTES: u64 = 256 << 20; +/// Bound on `model.safetensors.index.json`. +const MAX_INDEX_JSON_BYTES: u64 = 64 << 20; + +/// One tensor's dtype, shape and absolute byte range in its shard. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct TensorInfo { + pub dtype: String, + pub shape: Vec, + pub start: u64, + pub end: u64, +} + +struct Shard { + file: File, + payload_start: u64, + file_len: u64, + header: serde_json::Map, +} + +/// A read-only view of a safetensors checkpoint directory. +pub struct Checkpoint { + dir: PathBuf, + weight_map: serde_json::Map, + shards: HashMap, +} + +fn ck(msg: impl Into) -> StoreError { + StoreError::Checkpoint(msg.into()) +} + +fn shard_path(dir: &Path, filename: &str) -> Result { + let mut c = Path::new(filename).components(); + match (c.next(), c.next()) { + (Some(Component::Normal(name)), None) if name == filename => Ok(dir.join(name)), + _ => Err(ck(format!( + "shard file name {filename:?} is not a plain name" + ))), + } +} + +impl Checkpoint { + pub fn open(dir: &Path) -> Result { + let f = File::open(dir.join("model.safetensors.index.json"))?; + let mut raw = Vec::new(); + f.take(MAX_INDEX_JSON_BYTES + 1).read_to_end(&mut raw)?; + if raw.len() as u64 > MAX_INDEX_JSON_BYTES { + return Err(ck("index json too large")); + } + let v: serde_json::Value = + serde_json::from_slice(&raw).map_err(|e| ck(format!("index json: {e}")))?; + let weight_map = v + .get("weight_map") + .and_then(|m| m.as_object()) + .cloned() + .ok_or_else(|| ck("index json: missing weight_map object"))?; + Ok(Self { + dir: dir.to_path_buf(), + weight_map, + shards: HashMap::new(), + }) + } + + pub fn dir(&self) -> &Path { + &self.dir + } + + fn shard_for(&mut self, name: &str) -> Result<&Shard, StoreError> { + let filename = self + .weight_map + .get(name) + .ok_or_else(|| StoreError::MissingTensor(name.to_string()))? + .as_str() + .ok_or_else(|| ck(format!("index: shard of {name} is not a string")))? + .to_string(); + if !self.shards.contains_key(&filename) { + let shard = open_shard(&shard_path(&self.dir, &filename)?)?; + self.shards.insert(filename.clone(), shard); + } + Ok(&self.shards[&filename]) + } + + /// The header entry of `name`, with its byte range checked against the shard. + pub fn info(&mut self, name: &str) -> Result { + let shard = self.shard_for(name)?; + let entry = shard + .header + .get(name) + .ok_or_else(|| StoreError::MissingTensor(name.to_string()))?; + let dtype = entry + .get("dtype") + .and_then(|v| v.as_str()) + .ok_or_else(|| ck(format!("{name}: no dtype")))? + .to_string(); + let shape = entry + .get("shape") + .and_then(|v| v.as_array()) + .ok_or_else(|| ck(format!("{name}: no shape")))? + .iter() + .map(|d| d.as_u64().ok_or_else(|| ck(format!("{name}: bad shape")))) + .collect::, _>>()?; + let offs = entry + .get("data_offsets") + .and_then(|v| v.as_array()) + .ok_or_else(|| ck(format!("{name}: no data_offsets")))?; + let (Some(s), Some(e), 2) = ( + offs.first().and_then(|v| v.as_u64()), + offs.get(1).and_then(|v| v.as_u64()), + offs.len(), + ) else { + return Err(ck(format!("{name}: data_offsets must hold two integers"))); + }; + let start = shard + .payload_start + .checked_add(s) + .ok_or(StoreError::Overflow)?; + let end = shard + .payload_start + .checked_add(e) + .ok_or(StoreError::Overflow)?; + if s > e || end > shard.file_len { + return Err(ck(format!("{name}: byte range outside the shard"))); + } + Ok(TensorInfo { + dtype, + shape, + start, + end, + }) + } + + /// Reads `name` after checking its dtype and shape. `max_bytes` bounds the read. + pub fn read( + &mut self, + name: &str, + dtype: &str, + shape: &[u64], + max_bytes: u64, + ) -> Result, StoreError> { + let info = self.info(name)?; + if info.dtype != dtype { + return Err(StoreError::DtypeMismatch { + name: name.to_string(), + found: info.dtype, + }); + } + if info.shape != shape { + return Err(StoreError::ShapeMismatch { + name: name.to_string(), + }); + } + let len = info.end - info.start; + if len > max_bytes { + return Err(StoreError::ObjectTooLarge { + len, + max: max_bytes, + }); + } + let mut out = vec![0u8; usize::try_from(len).map_err(|_| StoreError::Overflow)?]; + self.shard_for(name)? + .file + .read_exact_at(&mut out, info.start)?; + Ok(out) + } +} + +fn open_shard(path: &Path) -> Result { + let file = File::open(path)?; + let file_len = file.metadata()?.len(); + let mut prefix = [0u8; 8]; + file.read_exact_at(&mut prefix, 0)?; + let header_len = u64::from_le_bytes(prefix); + if header_len > MAX_HEADER_BYTES || header_len.saturating_add(8) > file_len { + return Err(ck("shard header length is invalid")); + } + let mut raw = vec![0u8; header_len as usize]; + file.read_exact_at(&mut raw, 8)?; + let header = match serde_json::from_slice(&raw) { + Ok(serde_json::Value::Object(m)) => m, + Ok(_) => return Err(ck("shard header is not a JSON object")), + Err(e) => return Err(ck(format!("shard header json: {e}"))), + }; + Ok(Shard { + file, + payload_start: 8 + header_len, + file_len, + header, + }) +} + +/// The Qwen3-MoE expert geometry the indexer needs. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Qwen3MoeExperts { + pub model_digest: [u8; 32], + pub hidden: u64, + pub moe_intermediate: u64, + pub experts: u32, +} + +impl Qwen3MoeExperts { + /// `(rows, cols)` of a projection's weight: gate/up `[i][h]`, down `[h][i]`. + pub fn shape(&self, p: Projection) -> (u64, u64) { + match p { + Projection::Gate | Projection::Up => (self.moe_intermediate, self.hidden), + Projection::Down => (self.hidden, self.moe_intermediate), + } + } + + /// The checkpoint name of a projection's weight (scales add `_scale_inv`). + pub fn weight_name(layer: u32, expert: u32, p: Projection) -> String { + format!( + "model.layers.{layer}.mlp.experts.{expert}.{}.weight", + p.checkpoint_name() + ) + } +} + +/// Reads one projection of one expert straight from the checkpoint (weights, +/// scales, scale dtype), with full dtype and shape checks. +pub fn read_expert( + ckpt: &mut Checkpoint, + shape: &Qwen3MoeExperts, + layer: u32, + expert: u32, + p: Projection, + max_bytes: u64, +) -> Result<(Vec, Vec, ScaleDtype), StoreError> { + if expert >= shape.experts { + return Err(StoreError::MissingTensor(format!( + "expert {expert} of {}", + shape.experts + ))); + } + let (rows, cols) = shape.shape(p); + let wname = Qwen3MoeExperts::weight_name(layer, expert, p); + let sname = format!("{wname}_scale_inv"); + let weights = ckpt.read(&wname, "F8_E4M3", &[rows, cols], max_bytes)?; + let sinfo = ckpt.info(&sname)?; + let sdt = ScaleDtype::from_safetensors(&sinfo.dtype).ok_or(StoreError::DtypeMismatch { + name: sname.clone(), + found: sinfo.dtype.clone(), + })?; + let sshape = [rows.div_ceil(FP8_BLOCK), cols.div_ceil(FP8_BLOCK)]; + let scales = ckpt.read(&sname, sdt.safetensors_name(), &sshape, max_bytes)?; + Ok((weights, scales, sdt)) +} + +fn inside(child: &Path, parent: &Path) -> bool { + match (child.canonicalize(), parent.canonicalize()) { + (Ok(c), Ok(p)) => c.starts_with(p), + _ => false, + } +} + +/// Indexes every gate, up and down projection of `experts` in `layers` into +/// `store`, in (layer, expert, projection) order, and commits the index. +/// Refuses a store root inside the checkpoint directory. Any missing tensor, +/// dtype or shape mismatch, or a key already bound to other content aborts +/// before the index is committed. +pub fn index_qwen3_moe( + ckpt: &mut Checkpoint, + shape: &Qwen3MoeExperts, + layers: core::ops::Range, + store: &mut ExpertStore, +) -> Result, StoreError> { + if inside(store.root(), ckpt.dir()) { + return Err(StoreError::StoreInsideCheckpoint); + } + let max = store.limits().max_object_bytes; + let mut out = Vec::new(); + for layer in layers { + for expert in 0..shape.experts { + for p in Projection::ALL { + let (w, s, sdt) = read_expert(ckpt, shape, layer, expert, p, max)?; + let (rows, cols) = shape.shape(p); + let key = ExpertKey { + model_digest: shape.model_digest, + layer, + expert, + projection: p, + quant: QuantFormat::Fp8E4m3Block128, + }; + out.push(store.put(key, rows, cols, sdt, &w, &s)?); + } + } + } + store.commit()?; + Ok(out) +} diff --git a/crates/aien-expert-store/src/lib.rs b/crates/aien-expert-store/src/lib.rs new file mode 100644 index 00000000..c4809a41 --- /dev/null +++ b/crates/aien-expert-store/src/lib.rs @@ -0,0 +1,46 @@ +//! Omega Expert Ribbon P1 (sc#629): a content-addressed store for FP8 expert +//! tensors and a bounded, verified read adapter. +//! +//! * [`format`]: the canonical artifact (one projection of one expert: a +//! 4096-byte header, the FP8 weight bytes and the block-128 scale bytes, +//! each 4096-aligned) and the versioned index keyed by +//! (model digest, layer, expert, projection, quantization) with the data +//! digest. The content address is SHA-256 of the canonical artifact bytes. +//! * [`store`]: the on-disk store. Objects and the index are written to a +//! private temporary file, synced, renamed into place and the directory +//! synced, so a crash leaves either the old or the new state. +//! * [`indexer`]: a deterministic, read-only checkpoint-to-artifact indexer +//! for Qwen3-MoE FP8 safetensors checkpoints. The checkpoint is never +//! opened for writing; the artifact keeps the original bytes unchanged. +//! * [`adapter`]: the bounded asynchronous read adapter (queue depth, in-flight +//! bytes, object size, deadline, cancellation) into caller-provided aligned +//! staging buffers. Every object is hashed and compared in constant time +//! before it is handed back as ready; on any failure the staging buffer is +//! scrubbed before the caller gets it back. +//! * [`source`]: the byte sources behind the adapter (buffered and direct file +//! reads behind one interface) and [`fake`], a deterministic in-memory source +//! with injectable faults for tests. +//! +//! Not in this crate: GPU slots, residency policy and decode wiring (sc#630 to +//! sc#632, omega#533). + +pub mod adapter; +pub mod error; +pub mod fake; +pub mod format; +pub mod indexer; +pub mod source; +pub mod staging; +pub mod store; + +pub use adapter::{ + CancelOutcome, Outcome, ReadAdapter, ReadCompletion, ReadLimits, ReadyExpert, Refused, Ticket, +}; +pub use error::{ReadError, StoreError}; +pub use format::{ + ArtifactHeader, ExpertKey, IndexEntry, Projection, QuantFormat, ScaleDtype, ALIGN, FP8_BLOCK, + HEADER_REGION, +}; +pub use source::{BlockReader, BlockSource, FileSource, IoMode}; +pub use staging::StagingBuffer; +pub use store::{ExpertStore, StoreLimits}; diff --git a/crates/aien-expert-store/src/source.rs b/crates/aien-expert-store/src/source.rs new file mode 100644 index 00000000..ce2dfc0d --- /dev/null +++ b/crates/aien-expert-store/src/source.rs @@ -0,0 +1,89 @@ +//! Byte sources behind the read adapter. Buffered and direct file reads share +//! one interface so the mode can be chosen by measurement (sc#629 open item: +//! the GB10 read-only receipt), not assumed. + +use crate::error::ReadError; +use crate::format::hex; +use std::fs::File; +use std::os::unix::fs::{FileExt, OpenOptionsExt}; +use std::path::PathBuf; + +/// Opens objects by content address. +pub trait BlockSource: Send + Sync + 'static { + fn open(&self, digest: &[u8; 32]) -> Result, ReadError>; +} + +/// One open object. `size` is the object length in bytes. `read_at` may return fewer bytes than asked (a short read); +/// `Ok(0)` means end of file. +pub trait BlockReader: Send { + fn size(&self) -> Result; + fn read_at(&mut self, offset: u64, dst: &mut [u8]) -> Result; +} + +/// How file objects are read. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum IoMode { + /// `pread` through the page cache. + Buffered, + /// `O_DIRECT` (Linux): offsets, lengths and the staging buffer are all + /// 4096-aligned by construction. Refused elsewhere, never silently + /// downgraded to buffered. + Direct, +} + +/// Objects under `/objects/`. +#[derive(Debug, Clone)] +pub struct FileSource { + objects_dir: PathBuf, + mode: IoMode, +} + +impl FileSource { + pub fn new(objects_dir: PathBuf, mode: IoMode) -> Self { + Self { objects_dir, mode } + } + + pub fn mode(&self) -> IoMode { + self.mode + } +} + +struct FileReader(File); + +impl BlockReader for FileReader { + fn size(&self) -> Result { + Ok(self.0.metadata()?.len()) + } + + fn read_at(&mut self, offset: u64, dst: &mut [u8]) -> Result { + loop { + match self.0.read_at(dst, offset) { + Ok(n) => return Ok(n), + Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue, + Err(e) => return Err(e.into()), + } + } + } +} + +impl BlockSource for FileSource { + fn open(&self, digest: &[u8; 32]) -> Result, ReadError> { + let base = libc::O_NOFOLLOW | libc::O_CLOEXEC; + let flags = match self.mode { + IoMode::Buffered => base, + #[cfg(target_os = "linux")] + IoMode::Direct => base | libc::O_DIRECT, + #[cfg(not(target_os = "linux"))] + IoMode::Direct => return Err(ReadError::DirectIoUnsupported), + }; + let file = std::fs::OpenOptions::new() + .read(true) + .custom_flags(flags) + .open(self.objects_dir.join(hex(digest))) + .map_err(|e| match e.raw_os_error() { + Some(libc::EINVAL) if self.mode == IoMode::Direct => ReadError::DirectIoUnsupported, + _ => ReadError::from(e), + })?; + Ok(Box::new(FileReader(file))) + } +} diff --git a/crates/aien-expert-store/src/staging.rs b/crates/aien-expert-store/src/staging.rs new file mode 100644 index 00000000..3d4dc3e8 --- /dev/null +++ b/crates/aien-expert-store/src/staging.rs @@ -0,0 +1,77 @@ +//! Caller-provided staging buffers: 4096-aligned (so the direct read mode can +//! use them), zeroed at allocation and scrubbed on drop. +//! +//! A buffer handed to the adapter is owned by the job until its terminal +//! completion, so the caller cannot observe bytes that have not been verified. +//! On failure or cancellation the adapter scrubs it before handing it back. + +use crate::format::ALIGN; +use std::alloc::{alloc_zeroed, dealloc, handle_alloc_error, Layout}; +use std::ptr::NonNull; +use zeroize::Zeroize; + +pub struct StagingBuffer { + ptr: NonNull, + cap: usize, +} + +// SAFETY: the buffer is a uniquely owned heap allocation (like `Box<[u8]>`); +// no interior aliasing is shared across threads. +unsafe impl Send for StagingBuffer {} +// SAFETY: shared references only give `&[u8]`. +unsafe impl Sync for StagingBuffer {} + +impl StagingBuffer { + /// A zeroed buffer of at least `cap` bytes, rounded up to a 4096 multiple. + /// `None` when `cap` is zero or the rounded size overflows. + pub fn new(cap: usize) -> Option { + if cap == 0 { + return None; + } + let align = ALIGN as usize; + let cap = cap.checked_add(align - 1)? / align * align; + let layout = Layout::from_size_align(cap, align).ok()?; + // SAFETY: layout has a nonzero size. + let raw = unsafe { alloc_zeroed(layout) }; + let ptr = NonNull::new(raw).unwrap_or_else(|| handle_alloc_error(layout)); + Some(Self { ptr, cap }) + } + + pub fn capacity(&self) -> usize { + self.cap + } + + pub fn as_slice(&self) -> &[u8] { + // SAFETY: ptr is valid for cap initialised bytes for the life of self. + unsafe { std::slice::from_raw_parts(self.ptr.as_ptr(), self.cap) } + } + + pub fn as_mut_slice(&mut self) -> &mut [u8] { + // SAFETY: unique access through &mut self. + unsafe { std::slice::from_raw_parts_mut(self.ptr.as_ptr(), self.cap) } + } + + /// Overwrites every byte with zero (not elided by the optimiser). + pub fn scrub(&mut self) { + self.as_mut_slice().zeroize(); + } +} + +impl Drop for StagingBuffer { + fn drop(&mut self) { + self.scrub(); + // SAFETY: allocated in `new` with this exact layout. + unsafe { + dealloc( + self.ptr.as_ptr(), + Layout::from_size_align_unchecked(self.cap, ALIGN as usize), + ) + }; + } +} + +impl core::fmt::Debug for StagingBuffer { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + write!(f, "StagingBuffer({} bytes)", self.cap) + } +} diff --git a/crates/aien-expert-store/src/store.rs b/crates/aien-expert-store/src/store.rs new file mode 100644 index 00000000..70ed66bb --- /dev/null +++ b/crates/aien-expert-store/src/store.rs @@ -0,0 +1,254 @@ +//! The on-disk expert store. +//! +//! ```text +//! /objects/ one artifact per file, named by its content address +//! /index-v1 the committed index (see `format`) +//! /tmp/ private temporaries, removed on open +//! ``` +//! +//! Crash safety: every file is written to a fresh temporary (`O_EXCL`, mode +//! 0600), synced, renamed into place and its directory synced. An object is +//! durable before `put` returns; the index is replaced atomically by +//! `commit`, so after a crash the store holds either the old or the new index +//! and every object either index names. Orphan objects are harmless. +//! +//! Bounded memory: the store holds only the index (`max_entries` entries); +//! `put` holds one artifact (`max_object_bytes`). + +use crate::error::StoreError; +use crate::format::{ + build_artifact, decode_index, digest_eq, encode_index, hex, max_index_bytes, sha256, ExpertKey, + IndexEntry, ScaleDtype, +}; +use crate::source::{FileSource, IoMode}; +use std::collections::BTreeMap; +use std::fs::{File, OpenOptions}; +use std::io::{Read, Write}; +use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; + +pub const INDEX_FILE: &str = "index-v1"; +static TMP_COUNTER: AtomicU64 = AtomicU64::new(0); + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct StoreLimits { + pub max_entries: usize, + pub max_object_bytes: u64, +} + +impl Default for StoreLimits { + fn default() -> Self { + // One Qwen3-30B-A3B checkpoint: 48 layers x 128 experts x 3 projections. + Self { + max_entries: 48 * 128 * 3, + max_object_bytes: 64 << 20, + } + } +} + +pub struct ExpertStore { + root: PathBuf, + limits: StoreLimits, + entries: BTreeMap, +} + +const OPEN_FLAGS: i32 = libc::O_NOFOLLOW | libc::O_CLOEXEC; + +fn sync_dir(dir: &Path) -> Result<(), StoreError> { + File::open(dir)?.sync_all()?; + Ok(()) +} + +fn ensure_dir(dir: &Path) -> Result<(), StoreError> { + match std::fs::DirBuilder::new().mode(0o700).create(dir) { + Ok(()) => Ok(()), + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => { + if std::fs::symlink_metadata(dir)?.is_dir() { + Ok(()) + } else { + Err(StoreError::Io(std::io::ErrorKind::NotADirectory)) + } + } + Err(e) => Err(e.into()), + } +} + +/// Reads a whole file of at most `max` bytes without following a symlink. +fn read_bounded(path: &Path, max: u64) -> Result, StoreError> { + let f = OpenOptions::new() + .read(true) + .custom_flags(OPEN_FLAGS) + .open(path)?; + let len = f.metadata()?.len(); + if len > max { + return Err(StoreError::ObjectTooLarge { len, max }); + } + let mut out = Vec::with_capacity(len as usize); + f.take(max + 1).read_to_end(&mut out)?; + if out.len() as u64 > max { + return Err(StoreError::ObjectTooLarge { + len: out.len() as u64, + max, + }); + } + Ok(out) +} + +impl ExpertStore { + /// Opens (creating if needed) the store at `root`, removes temporaries + /// left by a crash, and loads and validates the committed index. + pub fn open(root: &Path, limits: StoreLimits) -> Result { + ensure_dir(root)?; + ensure_dir(&root.join("objects"))?; + let tmp = root.join("tmp"); + ensure_dir(&tmp)?; + for e in std::fs::read_dir(&tmp)? { + let e = e?; + if e.file_type()?.is_file() { + std::fs::remove_file(e.path())?; + } + } + let mut entries = BTreeMap::new(); + match read_bounded(&root.join(INDEX_FILE), max_index_bytes(limits.max_entries)) { + Ok(bytes) => { + for e in decode_index(&bytes, limits.max_entries)? { + if e.object_len > limits.max_object_bytes { + return Err(StoreError::ObjectTooLarge { + len: e.object_len, + max: limits.max_object_bytes, + }); + } + entries.insert(e.key, e); + } + } + Err(StoreError::Io(std::io::ErrorKind::NotFound)) => {} + Err(StoreError::ObjectTooLarge { .. }) => return Err(StoreError::TooManyEntries), + Err(e) => return Err(e), + } + Ok(Self { + root: root.to_path_buf(), + limits, + entries, + }) + } + + pub fn root(&self) -> &Path { + &self.root + } + + pub fn limits(&self) -> StoreLimits { + self.limits + } + + pub fn objects_dir(&self) -> PathBuf { + self.root.join("objects") + } + + /// A read source over this store's objects. + pub fn file_source(&self, mode: IoMode) -> FileSource { + FileSource::new(self.objects_dir(), mode) + } + + /// Entries in key order (committed plus staged by `put`). + pub fn entries(&self) -> impl Iterator { + self.entries.values() + } + + pub fn len(&self) -> usize { + self.entries.len() + } + + pub fn is_empty(&self) -> bool { + self.entries.is_empty() + } + + /// Index lookup only, no I/O. + pub fn get(&self, key: &ExpertKey) -> Option { + self.entries.get(key).copied() + } + + /// Writes one artifact durably and stages its index entry (persisted by + /// [`ExpertStore::commit`]). Putting the same key with the same content is + /// idempotent; the same key with other content is + /// [`StoreError::DuplicateKey`]. + pub fn put( + &mut self, + key: ExpertKey, + rows: u64, + cols: u64, + scale_dtype: ScaleDtype, + weights: &[u8], + scales: &[u8], + ) -> Result { + let (hdr, bytes) = build_artifact( + key, + rows, + cols, + scale_dtype, + weights, + scales, + self.limits.max_object_bytes, + )?; + let entry = IndexEntry { + key, + data_digest: sha256(&bytes), + object_len: hdr.object_len, + }; + match self.entries.get(&key) { + Some(old) if old == &entry => {} + Some(_) => return Err(StoreError::DuplicateKey(key)), + None if self.entries.len() >= self.limits.max_entries => { + return Err(StoreError::TooManyEntries) + } + None => {} + } + let name = hex(&entry.data_digest); + let objects = self.objects_dir(); + // An existing object is reused only if it still hashes to its name; + // a damaged one is replaced. + let present = match read_bounded(&objects.join(&name), self.limits.max_object_bytes) { + Ok(existing) => digest_eq(&sha256(&existing), &entry.data_digest), + Err(StoreError::Io(std::io::ErrorKind::NotFound)) + | Err(StoreError::ObjectTooLarge { .. }) => false, + Err(e) => return Err(e), + }; + if !present { + self.write_atomic(&objects, &name, &bytes)?; + } + self.entries.insert(key, entry); + Ok(entry) + } + + /// Atomically replaces the on-disk index with the current entries. + pub fn commit(&self) -> Result<(), StoreError> { + let entries: Vec = self.entries.values().copied().collect(); + let bytes = encode_index(&entries)?; + self.write_atomic(&self.root, INDEX_FILE, &bytes) + } + + fn write_atomic(&self, dir: &Path, name: &str, bytes: &[u8]) -> Result<(), StoreError> { + let tmp = self.root.join("tmp").join(format!( + "{name}.{}.{}", + std::process::id(), + TMP_COUNTER.fetch_add(1, Ordering::Relaxed) + )); + let result = (|| { + let mut f = OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o600) + .custom_flags(OPEN_FLAGS) + .open(&tmp)?; + f.write_all(bytes)?; + f.sync_all()?; + drop(f); + std::fs::rename(&tmp, dir.join(name))?; + sync_dir(dir) + })(); + if result.is_err() { + let _ = std::fs::remove_file(&tmp); + } + result + } +} diff --git a/crates/aien-expert-store/tests/adapter_tests.rs b/crates/aien-expert-store/tests/adapter_tests.rs new file mode 100644 index 00000000..dde2b340 --- /dev/null +++ b/crates/aien-expert-store/tests/adapter_tests.rs @@ -0,0 +1,359 @@ +//! The bounded read adapter over the deterministic fake source: verification +//! before ready, scrubbing on failure, every bound, deadlines, cancellation +//! and concurrent readers. + +mod common; + +use aien_expert_store::fake::{FakeSource, Fault}; +use aien_expert_store::{ + CancelOutcome, IndexEntry, Outcome, Projection, ReadAdapter, ReadCompletion, ReadError, + ReadLimits, StagingBuffer, +}; +use common::*; +use std::io::ErrorKind; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +const WAIT: Duration = Duration::from_secs(10); + +fn limits() -> ReadLimits { + ReadLimits { + max_in_flight: 2, + max_inflight_bytes: 1 << 20, + max_object_bytes: 512 << 10, + chunk_bytes: 4096, + } +} + +fn setup(lim: ReadLimits) -> (FakeSource, ReadAdapter, IndexEntry, Vec, Vec) { + let fake = FakeSource::new(); + let (e, bytes, w, s) = artifact(key(1, 2, Projection::Up), 192, 256, 3); + fake.insert(e.data_digest, bytes); + let a = ReadAdapter::new(Arc::new(fake.clone()), lim).unwrap(); + (fake, a, e, w, s) +} + +fn far() -> Instant { + Instant::now() + Duration::from_secs(30) +} + +fn buf(e: &IndexEntry) -> StagingBuffer { + StagingBuffer::new(e.object_len as usize).unwrap() +} + +fn one(a: &ReadAdapter, e: IndexEntry) -> ReadCompletion { + let t = a.submit(e, buf(&e), far()).unwrap(); + let c = a.wait(WAIT).expect("terminal"); + assert_eq!(c.ticket, t); + c +} + +fn expect_failed(c: ReadCompletion) -> ReadError { + match c.outcome { + Outcome::Failed { error, buf } => { + assert!( + buf.as_slice().iter().all(|&b| b == 0), + "buffer not scrubbed" + ); + error + } + o => panic!("expected Failed, got {o:?}"), + } +} + +#[test] +fn ready_only_after_verification_and_bytes_round_trip() { + let (_f, a, e, w, s) = setup(limits()); + match one(&a, e).outcome { + Outcome::Ready(r) => { + assert_eq!(r.weights(), &w[..]); + assert_eq!(r.scales(), &s[..]); + assert_eq!(r.header.key, e.key); + assert_eq!(r.artifact().len() as u64, e.object_len); + } + o => panic!("{o:?}"), + } + assert_eq!(a.in_flight(), (0, 0)); +} + +#[test] +fn corruption_is_a_digest_mismatch_and_scrubs() { + let (f, a, e, _, _) = setup(limits()); + for at in [0u64, 5000, e.object_len - 1] { + f.set_fault(e.data_digest, Fault::CorruptByte(at)); + assert_eq!( + expect_failed(one(&a, e)), + ReadError::DigestMismatch, + "at {at}" + ); + } +} + +#[test] +fn truncation_eof_and_io_errors_are_explicit() { + let (f, a, e, _, _) = setup(limits()); + f.set_fault(e.data_digest, Fault::Truncate(e.object_len - 4096)); + assert_eq!( + expect_failed(one(&a, e)), + ReadError::LengthMismatch { + expected: e.object_len, + found: e.object_len - 4096 + } + ); + f.set_fault(e.data_digest, Fault::EofAt(8192 + 100)); + assert_eq!( + expect_failed(one(&a, e)), + ReadError::UnexpectedEof { + read: 8192 + 100, + expected: e.object_len + } + ); + f.set_fault(e.data_digest, Fault::IoError(ErrorKind::Other)); + assert_eq!(expect_failed(one(&a, e)), ReadError::Io(ErrorKind::Other)); +} + +#[test] +fn short_reads_are_resumed_not_trusted() { + let (f, a, e, w, _) = setup(limits()); + f.set_fault(e.data_digest, Fault::ShortReads(1000)); + match one(&a, e).outcome { + Outcome::Ready(r) => assert_eq!(r.weights(), &w[..]), + o => panic!("{o:?}"), + } + assert!(f.reads() as u64 >= e.object_len / 1000); +} + +#[test] +fn wrong_hash_wrong_object_and_wrong_key_are_refused() { + let (f, a, e, _, _) = setup(limits()); + // Index digest names no object. + let mut missing = e; + missing.data_digest[0] ^= 1; + assert_eq!(expect_failed(one(&a, missing)), ReadError::NotFound); + // The object stored under the digest is a different (valid) artifact. + let (other, other_bytes, _, _) = artifact(key(1, 2, Projection::Up), 192, 256, 77); + assert_ne!(other.data_digest, e.data_digest); + f.insert(e.data_digest, other_bytes.clone()); + assert_eq!(expect_failed(one(&a, e)), ReadError::DigestMismatch); + // The digest matches, but the index entry claims another key. + f.insert(other.data_digest, other_bytes); + let mut lying = other; + lying.key = key(9, 9, Projection::Down); + assert_eq!(expect_failed(one(&a, lying)), ReadError::HeaderMismatch); +} + +#[test] +fn submit_bounds_refuse_and_return_the_buffer() { + let (f, a, e, _, _) = setup(limits()); + // Insufficient capacity. + let small = StagingBuffer::new(4096).unwrap(); + let r = a.submit(e, small, far()).unwrap_err(); + assert_eq!( + r.error, + ReadError::InsufficientCapacity { + need: e.object_len, + have: 4096 + } + ); + assert_eq!(r.buf.capacity(), 4096); + // Object larger than max_object_bytes. + let mut huge = e; + huge.object_len = 1 << 20; + let r = a + .submit(huge, StagingBuffer::new(1 << 20).unwrap(), far()) + .unwrap_err(); + assert_eq!(r.error, ReadError::ObjectTooLarge); + // Malformed entry length. + let mut odd = e; + odd.object_len = 4097; + assert_eq!( + a.submit(odd, buf(&e), far()).unwrap_err().error, + ReadError::InvalidEntry + ); + // Deadline already passed. + let r = a.submit(e, buf(&e), Instant::now()).unwrap_err(); + assert_eq!(r.error, ReadError::DeadlineExceeded); + // Queue depth: hold the device, fill both slots, the third is refused. + f.hold(); + let t1 = a.submit(e, buf(&e), far()).unwrap(); + let t2 = a.submit(e, buf(&e), far()).unwrap(); + assert_eq!( + a.submit(e, buf(&e), far()).unwrap_err().error, + ReadError::QueueFull + ); + assert_eq!(a.in_flight(), (2, 2 * e.object_len)); + f.release(); + let mut got = vec![a.wait(WAIT).unwrap().ticket, a.wait(WAIT).unwrap().ticket]; + got.sort(); + assert_eq!(got, vec![t1, t2]); + assert_eq!(a.in_flight(), (0, 0)); +} + +#[test] +fn inflight_byte_budget_is_enforced() { + let fake = FakeSource::new(); + let (e, bytes, _, _) = artifact(key(0, 0, Projection::Gate), 192, 256, 1); + fake.insert(e.data_digest, bytes); + let lim = ReadLimits { + max_in_flight: 8, + max_inflight_bytes: e.object_len * 2 + 1, + ..limits() + }; + let a = ReadAdapter::new(Arc::new(fake.clone()), lim).unwrap(); + fake.hold(); + a.submit(e, buf(&e), far()).unwrap(); + a.submit(e, buf(&e), far()).unwrap(); + assert_eq!( + a.submit(e, buf(&e), far()).unwrap_err().error, + ReadError::InflightBytesExceeded + ); + fake.release(); + for _ in 0..2 { + assert!(matches!(a.wait(WAIT).unwrap().outcome, Outcome::Ready(_))); + } +} + +#[test] +fn invalid_limits_are_refused() { + let src = Arc::new(FakeSource::new()); + for lim in [ + ReadLimits { + max_in_flight: 0, + ..limits() + }, + ReadLimits { + max_inflight_bytes: 0, + ..limits() + }, + ReadLimits { + max_object_bytes: 0, + ..limits() + }, + ReadLimits { + chunk_bytes: 1000, + ..limits() + }, + ] { + assert_eq!( + ReadAdapter::new(src.clone(), lim).err(), + Some(ReadError::InvalidLimits) + ); + } +} + +#[test] +fn a_stalled_read_hits_its_deadline_with_no_ready_state() { + let (f, a, e, _, _) = setup(limits()); + f.set_fault(e.data_digest, Fault::Delay(Duration::from_millis(20))); + let t0 = Instant::now(); + a.submit(e, buf(&e), Instant::now() + Duration::from_millis(60)) + .unwrap(); + let c = a.wait(WAIT).unwrap(); + assert_eq!(expect_failed(c), ReadError::DeadlineExceeded); + // Detected within a few chunk delays, not after the whole object. + assert!(t0.elapsed() < Duration::from_secs(2)); + assert_eq!(a.in_flight(), (0, 0)); +} + +#[test] +fn cancellation_yields_one_scrubbed_terminal() { + let (f, a, e, _, _) = setup(limits()); + f.hold(); + let t = a.submit(e, buf(&e), far()).unwrap(); + assert_eq!(a.cancel(t), CancelOutcome::Requested); + f.release(); + let c = a.wait(WAIT).unwrap(); + assert_eq!(c.ticket, t); + match c.outcome { + Outcome::Cancelled { buf } => assert!(buf.as_slice().iter().all(|&b| b == 0)), + o => panic!("{o:?}"), + } + assert!( + a.wait(Duration::from_millis(50)).is_none(), + "exactly one terminal" + ); + assert_eq!(a.cancel(t), CancelOutcome::Unknown); +} + +#[test] +fn concurrent_readers_respect_queue_depth_and_all_verify() { + let fake = FakeSource::new(); + let mut entries = Vec::new(); + for ex in 0..8u32 { + let (e, bytes, w, _) = artifact(key(0, ex, Projection::Gate), 192, 256, ex); + fake.insert(e.data_digest, bytes); + entries.push((e, w)); + } + fake.set_fault(entries[3].0.data_digest, Fault::CorruptByte(9000)); + let lim = ReadLimits { + max_in_flight: 4, + max_inflight_bytes: 64 << 20, + ..limits() + }; + let a = Arc::new(ReadAdapter::new(Arc::new(fake.clone()), lim).unwrap()); + let readers: Vec<_> = (0..6) + .map(|t| { + let a = Arc::clone(&a); + let entries = entries.clone(); + std::thread::spawn(move || { + let mut submitted = 0; + for i in 0..16 { + let (e, _) = entries[(t + i) % entries.len()]; + let mut b = buf(&e); + loop { + match a.submit(e, b, far()) { + Ok(_) => break, + Err(r) => { + assert_eq!(r.error, ReadError::QueueFull); + b = r.buf; + std::thread::yield_now(); + } + } + } + submitted += 1; + } + submitted + }) + }) + .collect(); + let total: usize = readers.into_iter().map(|h| h.join().unwrap()).sum(); + let (mut ok, mut bad) = (0, 0); + for _ in 0..total { + match a.wait(WAIT).expect("terminal").outcome { + Outcome::Ready(r) => { + let (_, w) = entries.iter().find(|(e, _)| e.key == r.header.key).unwrap(); + assert_eq!(r.weights(), &w[..]); + ok += 1; + } + Outcome::Failed { error, buf } => { + assert_eq!(error, ReadError::DigestMismatch); + assert!(buf.as_slice().iter().all(|&b| b == 0)); + bad += 1; + } + o => panic!("{o:?}"), + } + } + assert_eq!(ok + bad, 96); + assert_eq!( + bad, 12, + "every read of the corrupt object fails, no other does" + ); + assert!(fake.peak() <= 4, "peak {} exceeds queue depth", fake.peak()); + assert_eq!(a.in_flight(), (0, 0)); +} + +#[test] +fn drop_cancels_queued_reads_and_joins() { + let (f, a, e, _, _) = setup(limits()); + f.hold(); + a.submit(e, buf(&e), far()).unwrap(); + let releaser = { + let f = f.clone(); + std::thread::spawn(move || { + std::thread::sleep(Duration::from_millis(50)); + f.release(); + }) + }; + drop(a); + releaser.join().unwrap(); +} diff --git a/crates/aien-expert-store/tests/common/mod.rs b/crates/aien-expert-store/tests/common/mod.rs new file mode 100644 index 00000000..27c5aa7f --- /dev/null +++ b/crates/aien-expert-store/tests/common/mod.rs @@ -0,0 +1,173 @@ +#![allow(dead_code)] + +use aien_expert_store::format::build_artifact; +use aien_expert_store::{ExpertKey, IndexEntry, Projection, QuantFormat, ScaleDtype}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; + +pub const MODEL: [u8; 32] = [7u8; 32]; + +pub fn key(layer: u32, expert: u32, projection: Projection) -> ExpertKey { + ExpertKey { + model_digest: MODEL, + layer, + expert, + projection, + quant: QuantFormat::Fp8E4m3Block128, + } +} + +/// Deterministic filler (no randomness). +pub fn pattern(len: usize, seed: u32) -> Vec { + let mut x = seed.wrapping_mul(2_654_435_761).wrapping_add(1); + (0..len) + .map(|_| { + x ^= x << 13; + x ^= x >> 17; + x ^= x << 5; + (x >> 8) as u8 + }) + .collect() +} + +/// A canonical artifact and its index entry for a `[rows][cols]` projection. +pub fn artifact( + k: ExpertKey, + rows: u64, + cols: u64, + seed: u32, +) -> (IndexEntry, Vec, Vec, Vec) { + let w = pattern((rows * cols) as usize, seed); + let s = pattern( + (rows.div_ceil(128) * cols.div_ceil(128) * 2) as usize, + seed + 1, + ); + let (h, bytes) = build_artifact(k, rows, cols, ScaleDtype::Bf16, &w, &s, u64::MAX).unwrap(); + let e = IndexEntry { + key: k, + data_digest: aien_expert_store::format::sha256(&bytes), + object_len: h.object_len, + }; + (e, bytes, w, s) +} + +static DIR_COUNTER: AtomicU64 = AtomicU64::new(0); + +/// A fresh empty directory under the system temp dir, removed on drop. +pub struct TempDir(pub PathBuf); + +impl TempDir { + pub fn new(tag: &str) -> Self { + let p = std::env::temp_dir().join(format!( + "aien-expert-store-{tag}-{}-{}", + std::process::id(), + DIR_COUNTER.fetch_add(1, Ordering::Relaxed) + )); + let _ = std::fs::remove_dir_all(&p); + std::fs::create_dir_all(&p).unwrap(); + Self(p) + } + + pub fn path(&self) -> &Path { + &self.0 + } +} + +impl Drop for TempDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +/// One tensor for [`write_shard`]. +pub struct T { + pub name: String, + pub dtype: &'static str, + pub shape: Vec, + pub data: Vec, +} + +/// Writes a safetensors file holding `tensors` in order. +pub fn write_shard(path: &Path, tensors: &[T]) { + let mut header = serde_json::Map::new(); + let mut off = 0u64; + for t in tensors { + let end = off + t.data.len() as u64; + header.insert( + t.name.clone(), + serde_json::json!({"dtype": t.dtype, "shape": t.shape, "data_offsets": [off, end]}), + ); + off = end; + } + let h = serde_json::to_vec(&serde_json::Value::Object(header)).unwrap(); + let mut out = (h.len() as u64).to_le_bytes().to_vec(); + out.extend_from_slice(&h); + for t in tensors { + out.extend_from_slice(&t.data); + } + std::fs::write(path, out).unwrap(); +} + +pub const H: u64 = 256; +pub const I: u64 = 192; // not a block multiple: exercises the ceil scale shape +pub const LAYERS: u32 = 2; +pub const EXPERTS: u32 = 3; + +pub fn proj_shape(p: Projection) -> (u64, u64) { + match p { + Projection::Gate | Projection::Up => (I, H), + Projection::Down => (H, I), + } +} + +/// A tiny Qwen3-MoE FP8 checkpoint: layer `l` in shard `l`, BF16 scales, +/// plus a non-expert tensor. Returns the expected (weights, scales) per key. +pub fn write_checkpoint(dir: &Path) -> Vec<(ExpertKey, Vec, Vec)> { + let mut expected = Vec::new(); + let mut weight_map = serde_json::Map::new(); + for l in 0..LAYERS { + let shard = format!("model-{:05}-of-{:05}.safetensors", l + 1, LAYERS); + let mut ts = vec![T { + name: format!("model.layers.{l}.mlp.gate.weight"), + dtype: "BF16", + shape: vec![EXPERTS as u64, H], + data: pattern((EXPERTS as u64 * H * 2) as usize, 999 + l), + }]; + for e in 0..EXPERTS { + for p in Projection::ALL { + let (r, c) = proj_shape(p); + let seed = l * 100 + e * 10 + p as u32; + let w = pattern((r * c) as usize, seed); + let s = pattern( + (r.div_ceil(128) * c.div_ceil(128) * 2) as usize, + seed + 5000, + ); + let base = format!("model.layers.{l}.mlp.experts.{e}.{}", p.checkpoint_name()); + ts.push(T { + name: format!("{base}.weight"), + dtype: "F8_E4M3", + shape: vec![r, c], + data: w.clone(), + }); + ts.push(T { + name: format!("{base}.weight_scale_inv"), + dtype: "BF16", + shape: vec![r.div_ceil(128), c.div_ceil(128)], + data: s.clone(), + }); + expected.push((key(l, e, p), w, s)); + } + } + for t in &ts { + weight_map.insert(t.name.clone(), serde_json::Value::String(shard.clone())); + } + write_shard(&dir.join(&shard), &ts); + } + let index = serde_json::json!({"metadata": {}, "weight_map": weight_map}); + std::fs::write( + dir.join("model.safetensors.index.json"), + serde_json::to_vec(&index).unwrap(), + ) + .unwrap(); + expected +} diff --git a/crates/aien-expert-store/tests/format_store_tests.rs b/crates/aien-expert-store/tests/format_store_tests.rs new file mode 100644 index 00000000..20b5b1ed --- /dev/null +++ b/crates/aien-expert-store/tests/format_store_tests.rs @@ -0,0 +1,256 @@ +//! Artifact and index codecs, and the crash-safe on-disk store. + +mod common; + +use aien_expert_store::format::{decode_index, encode_index, hex, sha256}; +use aien_expert_store::store::INDEX_FILE; +use aien_expert_store::{ + ArtifactHeader, ExpertStore, Projection, ScaleDtype, StoreError, StoreLimits, ALIGN, + HEADER_REGION, +}; +use common::*; + +#[test] +fn header_layout_is_aligned_and_round_trips() { + let h = ArtifactHeader::new(key(1, 2, Projection::Down), 200, 300, ScaleDtype::F32).unwrap(); + assert_eq!(h.weight_offset, HEADER_REGION as u64); + assert_eq!(h.weight_len, 60_000); + assert_eq!((h.scale_rows, h.scale_cols), (2, 3)); + assert_eq!(h.scale_len, 24); + assert!(h.scale_offset.is_multiple_of(ALIGN)); + assert!(h.object_len.is_multiple_of(ALIGN)); + assert_eq!(ArtifactHeader::decode(&h.encode()).unwrap(), h); +} + +#[test] +fn header_decode_refuses_any_tampered_field() { + let h = ArtifactHeader::new(key(0, 0, Projection::Gate), 128, 256, ScaleDtype::Bf16).unwrap(); + let good = h.encode(); + for (at, want) in [ + (0usize, StoreError::BadMagic), + (8, StoreError::UnsupportedVersion), + (12, StoreError::BadHeader("header_len")), + (56, StoreError::BadHeader("projection")), + (57, StoreError::BadHeader("quant")), + (58, StoreError::BadHeader("weight dtype")), + (59, StoreError::BadHeader("scale dtype")), + (60, StoreError::BadHeader("block")), + (104, StoreError::BadHeader("derived fields disagree")), + (4000, StoreError::BadHeader("nonzero reserved bytes")), + ] { + let mut b = good.clone(); + b[at] ^= 0x40; + assert_eq!(ArtifactHeader::decode(&b), Err(want), "byte {at}"); + } + assert!(ArtifactHeader::decode(&good[..100]).is_err()); +} + +#[test] +fn artifact_build_refuses_wrong_payload_lengths_and_size_bound() { + let k = key(0, 0, Projection::Up); + let w = vec![0u8; 128 * 128]; + let s = vec![0u8; 2]; + let build = aien_expert_store::format::build_artifact; + assert!(build(k, 128, 128, ScaleDtype::Bf16, &w, &s, u64::MAX).is_ok()); + assert!(matches!( + build(k, 128, 128, ScaleDtype::Bf16, &w[1..], &s, u64::MAX), + Err(StoreError::PayloadLength { .. }) + )); + assert!(matches!( + build(k, 128, 128, ScaleDtype::F32, &w, &s, u64::MAX), + Err(StoreError::PayloadLength { .. }) + )); + assert!(matches!( + build(k, 128, 128, ScaleDtype::Bf16, &w, &s, 4096), + Err(StoreError::ObjectTooLarge { .. }) + )); + assert_eq!( + build(k, u64::MAX, 2, ScaleDtype::Bf16, &w, &s, u64::MAX).unwrap_err(), + StoreError::Overflow + ); +} + +#[test] +fn index_round_trips_and_refuses_duplicates_tamper_and_oversize() { + let a = artifact(key(0, 0, Projection::Gate), 128, 128, 1).0; + let b = artifact(key(0, 1, Projection::Gate), 128, 128, 2).0; + let bytes = encode_index(&[a, b]).unwrap(); + assert_eq!(decode_index(&bytes, 2).unwrap(), vec![a, b]); + assert_eq!(decode_index(&bytes, 1), Err(StoreError::TooManyEntries)); + assert!(encode_index(&[a, a]).is_err()); + assert!(encode_index(&[b, a]).is_err()); + + let mut t = bytes.clone(); + t[30] ^= 1; + assert_eq!(decode_index(&t, 2), Err(StoreError::IndexChecksum)); + assert!(decode_index(&bytes[..bytes.len() - 1], 2).is_err()); + + // A duplicate key with a valid trailer is still refused. + let mut dup = bytes[..bytes.len() - 32].to_vec(); + let rec = dup[24..24 + 84].to_vec(); + dup[24 + 84..24 + 168].copy_from_slice(&rec); + let tr = sha256(&dup); + dup.extend_from_slice(&tr); + assert_eq!( + decode_index(&dup, 2), + Err(StoreError::BadIndex("entries not strictly ascending")) + ); +} + +#[test] +fn store_put_commit_reopen_and_idempotence() { + let d = TempDir::new("store"); + let mut s = ExpertStore::open(d.path(), StoreLimits::default()).unwrap(); + let k = key(3, 4, Projection::Down); + let (want, bytes, w, sc) = artifact(k, 256, 192, 9); + let e = s.put(k, 256, 192, ScaleDtype::Bf16, &w, &sc).unwrap(); + assert_eq!(e, want); + assert_eq!(s.put(k, 256, 192, ScaleDtype::Bf16, &w, &sc).unwrap(), want); + let on_disk = std::fs::read(d.path().join("objects").join(hex(&e.data_digest))).unwrap(); + assert_eq!(on_disk, bytes); + // Not visible to a reopen until committed. + assert!(ExpertStore::open(d.path(), StoreLimits::default()) + .unwrap() + .is_empty()); + s.commit().unwrap(); + let r = ExpertStore::open(d.path(), StoreLimits::default()).unwrap(); + assert_eq!(r.get(&k), Some(want)); + assert_eq!(r.len(), 1); +} + +#[test] +fn store_refuses_rebinding_a_key_to_other_content() { + let d = TempDir::new("dup"); + let mut s = ExpertStore::open(d.path(), StoreLimits::default()).unwrap(); + let k = key(0, 0, Projection::Gate); + let (_, _, w, sc) = artifact(k, 128, 128, 1); + s.put(k, 128, 128, ScaleDtype::Bf16, &w, &sc).unwrap(); + let mut w2 = w.clone(); + w2[0] ^= 1; + assert_eq!( + s.put(k, 128, 128, ScaleDtype::Bf16, &w2, &sc), + Err(StoreError::DuplicateKey(k)) + ); +} + +#[test] +fn store_bounds_entries_and_object_size() { + let d = TempDir::new("bounds"); + let lim = StoreLimits { + max_entries: 1, + max_object_bytes: 1 << 20, + }; + let mut s = ExpertStore::open(d.path(), lim).unwrap(); + let (_, _, w, sc) = artifact(key(0, 0, Projection::Gate), 128, 128, 1); + s.put( + key(0, 0, Projection::Gate), + 128, + 128, + ScaleDtype::Bf16, + &w, + &sc, + ) + .unwrap(); + assert_eq!( + s.put( + key(0, 1, Projection::Gate), + 128, + 128, + ScaleDtype::Bf16, + &w, + &sc + ), + Err(StoreError::TooManyEntries) + ); + let big = vec![0u8; 1024 * 1024]; + let bs = vec![0u8; 8 * 8 * 2]; + let mut s2 = ExpertStore::open(TempDir::new("b2").path(), lim).unwrap(); + assert!(matches!( + s2.put( + key(0, 0, Projection::Up), + 1024, + 1024, + ScaleDtype::Bf16, + &big, + &bs + ), + Err(StoreError::ObjectTooLarge { .. }) + )); + // A committed index with more entries than the limit is refused on open. + let mut s3 = ExpertStore::open(d.path(), StoreLimits::default()).unwrap(); + s3.put( + key(0, 1, Projection::Gate), + 128, + 128, + ScaleDtype::Bf16, + &w, + &sc, + ) + .unwrap(); + s3.put( + key(0, 0, Projection::Gate), + 128, + 128, + ScaleDtype::Bf16, + &w, + &sc, + ) + .unwrap(); + s3.commit().unwrap(); + assert!(matches!( + ExpertStore::open(d.path(), lim), + Err(StoreError::TooManyEntries) + )); +} + +#[test] +fn crash_leftovers_are_cleaned_and_a_torn_index_is_refused() { + let d = TempDir::new("crash"); + let mut s = ExpertStore::open(d.path(), StoreLimits::default()).unwrap(); + let k = key(0, 0, Projection::Gate); + let (_, _, w, sc) = artifact(k, 128, 128, 1); + s.put(k, 128, 128, ScaleDtype::Bf16, &w, &sc).unwrap(); + s.commit().unwrap(); + // A temporary left by a crash mid-write. + std::fs::write(d.path().join("tmp").join("index-v1.1.1"), b"partial").unwrap(); + let r = ExpertStore::open(d.path(), StoreLimits::default()).unwrap(); + assert_eq!(r.len(), 1); + assert_eq!(std::fs::read_dir(d.path().join("tmp")).unwrap().count(), 0); + // A torn index (not produced by our rename protocol) fails closed. + let p = d.path().join(INDEX_FILE); + let full = std::fs::read(&p).unwrap(); + std::fs::write(&p, &full[..full.len() - 7]).unwrap(); + assert!(ExpertStore::open(d.path(), StoreLimits::default()).is_err()); +} + +#[test] +fn put_replaces_a_damaged_existing_object() { + let d = TempDir::new("heal"); + let mut s = ExpertStore::open(d.path(), StoreLimits::default()).unwrap(); + let k = key(0, 0, Projection::Gate); + let (want, bytes, w, sc) = artifact(k, 128, 128, 1); + s.put(k, 128, 128, ScaleDtype::Bf16, &w, &sc).unwrap(); + let p = d.path().join("objects").join(hex(&want.data_digest)); + std::fs::write(&p, b"garbage").unwrap(); + let mut s2 = ExpertStore::open(d.path(), StoreLimits::default()).unwrap(); + s2.put(k, 128, 128, ScaleDtype::Bf16, &w, &sc).unwrap(); + assert_eq!(std::fs::read(&p).unwrap(), bytes); +} + +#[test] +fn objects_and_index_are_owner_only() { + use std::os::unix::fs::PermissionsExt; + let d = TempDir::new("perm"); + let mut s = ExpertStore::open(d.path(), StoreLimits::default()).unwrap(); + let k = key(0, 0, Projection::Gate); + let (want, _, w, sc) = artifact(k, 128, 128, 1); + s.put(k, 128, 128, ScaleDtype::Bf16, &w, &sc).unwrap(); + s.commit().unwrap(); + for p in [ + d.path().join("objects").join(hex(&want.data_digest)), + d.path().join(INDEX_FILE), + ] { + let mode = std::fs::metadata(p).unwrap().permissions().mode() & 0o777; + assert_eq!(mode, 0o600); + } +} diff --git a/crates/aien-expert-store/tests/indexer_file_tests.rs b/crates/aien-expert-store/tests/indexer_file_tests.rs new file mode 100644 index 00000000..da7402be --- /dev/null +++ b/crates/aien-expert-store/tests/indexer_file_tests.rs @@ -0,0 +1,295 @@ +//! Checkpoint indexer and the file-backed read path: random access to one +//! expert, byte-for-byte round trip against the checkpoint bytes, determinism, +//! read-only source, negative controls and on-disk damage. + +mod common; + +use aien_expert_store::format::hex; +use aien_expert_store::indexer::{index_qwen3_moe, read_expert, Checkpoint, Qwen3MoeExperts}; +use aien_expert_store::store::INDEX_FILE; +use aien_expert_store::{ + ExpertStore, IndexEntry, IoMode, Outcome, Projection, ReadAdapter, ReadError, ReadLimits, + StagingBuffer, StoreError, StoreLimits, +}; +use common::*; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +fn shape() -> Qwen3MoeExperts { + Qwen3MoeExperts { + model_digest: MODEL, + hidden: H, + moe_intermediate: I, + experts: EXPERTS, + } +} + +fn read_one(a: &ReadAdapter, e: IndexEntry) -> Outcome { + let b = StagingBuffer::new(e.object_len as usize).unwrap(); + a.submit(e, b, Instant::now() + Duration::from_secs(30)) + .unwrap(); + a.wait(Duration::from_secs(10)).unwrap().outcome +} + +fn dir_digest(dir: &std::path::Path) -> Vec<(String, [u8; 32])> { + let mut v: Vec<_> = std::fs::read_dir(dir) + .unwrap() + .map(|e| { + let p = e.unwrap().path(); + let d = aien_expert_store::format::sha256(&std::fs::read(&p).unwrap()); + (p.file_name().unwrap().to_string_lossy().into_owned(), d) + }) + .collect(); + v.sort(); + v +} + +#[test] +fn index_then_random_access_round_trips_byte_for_byte() { + let ck = TempDir::new("ckpt"); + let expected = write_checkpoint(ck.path()); + let before = dir_digest(ck.path()); + let st = TempDir::new("st"); + let mut store = ExpertStore::open(st.path(), StoreLimits::default()).unwrap(); + let mut ckpt = Checkpoint::open(ck.path()).unwrap(); + let entries = index_qwen3_moe(&mut ckpt, &shape(), 0..LAYERS, &mut store).unwrap(); + assert_eq!(entries.len(), (LAYERS * EXPERTS * 3) as usize); + assert_eq!( + dir_digest(ck.path()), + before, + "checkpoint must be untouched" + ); + + let store = ExpertStore::open(st.path(), StoreLimits::default()).unwrap(); + let a = ReadAdapter::new( + Arc::new(store.file_source(IoMode::Buffered)), + ReadLimits::default(), + ) + .unwrap(); + // Random access order, one expert at a time. + for i in [7usize, 0, 17, 3, 11, 16, 1] { + let (k, w, s) = &expected[i]; + let e = store.get(k).expect("indexed"); + match read_one(&a, e) { + Outcome::Ready(r) => { + assert_eq!(r.weights(), &w[..], "weights of {k:?}"); + assert_eq!(r.scales(), &s[..], "scales of {k:?}"); + } + o => panic!("{o:?}"), + } + // Same bytes as a direct read of the checkpoint tensor. + let mut c = Checkpoint::open(ck.path()).unwrap(); + let (dw, ds, _) = + read_expert(&mut c, &shape(), k.layer, k.expert, k.projection, u64::MAX).unwrap(); + assert_eq!((&dw, &ds), (w, s)); + } +} + +#[test] +fn indexing_is_deterministic() { + let ck = TempDir::new("det"); + write_checkpoint(ck.path()); + let (s1, s2) = (TempDir::new("d1"), TempDir::new("d2")); + for s in [&s1, &s2] { + let mut store = ExpertStore::open(s.path(), StoreLimits::default()).unwrap(); + let mut ckpt = Checkpoint::open(ck.path()).unwrap(); + index_qwen3_moe(&mut ckpt, &shape(), 0..LAYERS, &mut store).unwrap(); + } + assert_eq!( + std::fs::read(s1.path().join(INDEX_FILE)).unwrap(), + std::fs::read(s2.path().join(INDEX_FILE)).unwrap() + ); + assert_eq!( + dir_digest(&s1.path().join("objects")), + dir_digest(&s2.path().join("objects")) + ); +} + +#[test] +fn negative_controls_missing_dtype_shape_expert_and_store_location() { + let ck = TempDir::new("neg"); + write_checkpoint(ck.path()); + let st = TempDir::new("negst"); + let mut store = ExpertStore::open(st.path(), StoreLimits::default()).unwrap(); + let mut ckpt = Checkpoint::open(ck.path()).unwrap(); + + // Missing layer. + assert!(matches!( + index_qwen3_moe(&mut ckpt, &shape(), 0..LAYERS + 1, &mut store), + Err(StoreError::MissingTensor(_)) + )); + assert!( + !st.path().join(INDEX_FILE).exists(), + "nothing committed on failure" + ); + + // Shape mismatch (wrong hidden size). + let mut bad = shape(); + bad.hidden = H + 128; + assert!(matches!( + read_expert(&mut ckpt, &bad, 0, 0, Projection::Gate, u64::MAX), + Err(StoreError::ShapeMismatch { .. }) + )); + // Expert id out of range. + assert!(matches!( + read_expert(&mut ckpt, &shape(), 0, EXPERTS, Projection::Gate, u64::MAX), + Err(StoreError::MissingTensor(_)) + )); + // Read bound. + assert!(matches!( + read_expert(&mut ckpt, &shape(), 0, 0, Projection::Gate, 100), + Err(StoreError::ObjectTooLarge { .. }) + )); + // Store inside the checkpoint directory. + let inner = ck.path().join("store"); + let mut s2 = ExpertStore::open(&inner, StoreLimits::default()).unwrap(); + assert_eq!( + index_qwen3_moe(&mut ckpt, &shape(), 0..1, &mut s2).unwrap_err(), + StoreError::StoreInsideCheckpoint + ); +} + +#[test] +fn dtype_mismatch_and_hostile_shard_names_are_refused() { + let ck = TempDir::new("dt"); + let w = pattern((I * H) as usize, 1); + write_shard( + &ck.path().join("a.safetensors"), + &[ + T { + name: "model.layers.0.mlp.experts.0.gate_proj.weight".into(), + dtype: "BF16", + shape: vec![I, H], + data: w, + }, + T { + name: "model.layers.0.mlp.experts.0.up_proj.weight".into(), + dtype: "F8_E4M3", + shape: vec![I, H], + data: pattern((I * H) as usize, 2), + }, + T { + name: "model.layers.0.mlp.experts.0.up_proj.weight_scale_inv".into(), + dtype: "F16", + shape: vec![2, 2], + data: vec![0; 8], + }, + ], + ); + let index = serde_json::json!({"weight_map": { + "model.layers.0.mlp.experts.0.gate_proj.weight": "a.safetensors", + "model.layers.0.mlp.experts.0.up_proj.weight": "a.safetensors", + "model.layers.0.mlp.experts.0.up_proj.weight_scale_inv": "a.safetensors", + "model.layers.0.mlp.experts.0.down_proj.weight": "../escape.safetensors", + }}); + std::fs::write( + ck.path().join("model.safetensors.index.json"), + serde_json::to_vec(&index).unwrap(), + ) + .unwrap(); + let mut c = Checkpoint::open(ck.path()).unwrap(); + assert!(matches!( + read_expert(&mut c, &shape(), 0, 0, Projection::Gate, u64::MAX), + Err(StoreError::DtypeMismatch { .. }) + )); + assert!(matches!( + read_expert(&mut c, &shape(), 0, 0, Projection::Up, u64::MAX), + Err(StoreError::DtypeMismatch { .. }) + )); + assert!(matches!( + read_expert(&mut c, &shape(), 0, 0, Projection::Down, u64::MAX), + Err(StoreError::Checkpoint(_)) + )); +} + +#[test] +fn on_disk_damage_and_symlinks_fail_closed() { + let st = TempDir::new("dmg"); + let mut store = ExpertStore::open(st.path(), StoreLimits::default()).unwrap(); + let k = key(0, 0, Projection::Down); + let (_, _, w, s) = artifact(k, 256, 192, 4); + let e = store + .put(k, 256, 192, aien_expert_store::ScaleDtype::Bf16, &w, &s) + .unwrap(); + let a = ReadAdapter::new( + Arc::new(store.file_source(IoMode::Buffered)), + ReadLimits::default(), + ) + .unwrap(); + assert!(matches!(read_one(&a, e), Outcome::Ready(_))); + let p = st.path().join("objects").join(hex(&e.data_digest)); + let good = std::fs::read(&p).unwrap(); + + let mut flipped = good.clone(); + flipped[4096 + 10] ^= 0x80; + std::fs::write(&p, &flipped).unwrap(); + assert!(matches!( + read_one(&a, e), + Outcome::Failed { + error: ReadError::DigestMismatch, + .. + } + )); + + std::fs::write(&p, &good[..good.len() - 4096]).unwrap(); + assert!(matches!( + read_one(&a, e), + Outcome::Failed { + error: ReadError::LengthMismatch { .. }, + .. + } + )); + + // A planted symlink is not followed. + let elsewhere = st.path().join("elsewhere"); + std::fs::write(&elsewhere, &good).unwrap(); + std::fs::remove_file(&p).unwrap(); + std::os::unix::fs::symlink(&elsewhere, &p).unwrap(); + match read_one(&a, e) { + Outcome::Failed { + error: ReadError::Io(_), + buf, + } => { + assert!(buf.as_slice().iter().all(|&b| b == 0)) + } + o => panic!("{o:?}"), + } + + std::fs::remove_file(&p).unwrap(); + assert!(matches!( + read_one(&a, e), + Outcome::Failed { + error: ReadError::NotFound, + .. + } + )); +} + +#[test] +fn direct_mode_reads_verify_or_refuse_explicitly() { + let st = TempDir::new("direct"); + let mut store = ExpertStore::open(st.path(), StoreLimits::default()).unwrap(); + let k = key(0, 1, Projection::Gate); + let (_, _, w, s) = artifact(k, 192, 256, 5); + let e = store + .put(k, 192, 256, aien_expert_store::ScaleDtype::Bf16, &w, &s) + .unwrap(); + let a = ReadAdapter::new( + Arc::new(store.file_source(IoMode::Direct)), + ReadLimits::default(), + ) + .unwrap(); + match read_one(&a, e) { + Outcome::Ready(r) => { + assert_eq!(r.weights(), &w[..]); + eprintln!("direct mode: verified read"); + } + // Not Linux, or a file system without O_DIRECT (tmpfs): an explicit + // refusal, never a silent buffered fallback. + Outcome::Failed { + error: ReadError::DirectIoUnsupported, + .. + } => eprintln!("direct mode: refused (DirectIoUnsupported)"), + o => panic!("{o:?}"), + } +} diff --git a/crates/aien-inference-abi/Cargo.toml b/crates/aien-inference-abi/Cargo.toml index e9c7dae6..a177d1b9 100644 --- a/crates/aien-inference-abi/Cargo.toml +++ b/crates/aien-inference-abi/Cargo.toml @@ -40,3 +40,8 @@ dev-fallback = [] # a real `OmegaEngine` over a host bf16 pool, so other crates can test the persistent KV path # without a chip. Dev-dependencies only; never in a server build. host-test-engine = [] + +[dev-dependencies] +# sc#629: the expert store's random-access reads are checked byte for byte +# against this crate's resident-loader shard reader (tests only). +aien-expert-store = { path = "../aien-expert-store" } diff --git a/crates/aien-inference-abi/tests/expert_store_roundtrip.rs b/crates/aien-inference-abi/tests/expert_store_roundtrip.rs new file mode 100644 index 00000000..9b566eeb --- /dev/null +++ b/crates/aien-inference-abi/tests/expert_store_roundtrip.rs @@ -0,0 +1,156 @@ +//! sc#629 acceptance: random-access expert weight/scale reads from the +//! content-addressed expert store equal, byte for byte, what the resident +//! OWN-30B loader's shard reader (`ShardSource`, the source behind +//! `load_qwen3_moe_omega`) returns for the same FP8 checkpoint tensors. + +use aien_expert_store::indexer::{index_qwen3_moe, Checkpoint, Qwen3MoeExperts}; +use aien_expert_store::{ + ExpertKey, ExpertStore, IoMode, Outcome, Projection, QuantFormat, ReadAdapter, ReadLimits, + StagingBuffer, StoreLimits, +}; +use aien_inference_abi::qwen3_moe_omega::{ShardSource, TensorSource}; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +const H: usize = 256; +const I: usize = 192; +const LAYERS: u32 = 2; +const EXPERTS: u32 = 4; +const MODEL: [u8; 32] = [0x30; 32]; + +fn fill(len: usize, seed: u32) -> Vec { + let mut x = seed.wrapping_mul(2_654_435_761) | 1; + (0..len) + .map(|_| { + x ^= x << 13; + x ^= x >> 17; + x ^= x << 5; + (x >> 8) as u8 + }) + .collect() +} + +fn dims(p: Projection) -> (usize, usize) { + match p { + Projection::Gate | Projection::Up => (I, H), + Projection::Down => (H, I), + } +} + +fn write_checkpoint(dir: &Path) { + let mut weight_map = serde_json::Map::new(); + for l in 0..LAYERS { + let shard = format!("model-{:05}-of-{LAYERS:05}.safetensors", l + 1); + let mut header = serde_json::Map::new(); + let mut data = Vec::new(); + for e in 0..EXPERTS { + for p in Projection::ALL { + let (r, c) = dims(p); + let base = format!("model.layers.{l}.mlp.experts.{e}.{}", p.checkpoint_name()); + let seed = l * 1000 + e * 10 + p as u32; + for (name, dtype, shape, bytes) in [ + ( + format!("{base}.weight"), + "F8_E4M3", + vec![r, c], + fill(r * c, seed), + ), + ( + format!("{base}.weight_scale_inv"), + "BF16", + vec![r.div_ceil(128), c.div_ceil(128)], + fill(r.div_ceil(128) * c.div_ceil(128) * 2, seed + 7), + ), + ] { + let start = data.len(); + data.extend_from_slice(&bytes); + header.insert( + name.clone(), + serde_json::json!({"dtype": dtype, "shape": shape, "data_offsets": [start, data.len()]}), + ); + weight_map.insert(name, serde_json::Value::String(shard.clone())); + } + } + } + let h = serde_json::to_vec(&serde_json::Value::Object(header)).unwrap(); + let mut out = (h.len() as u64).to_le_bytes().to_vec(); + out.extend_from_slice(&h); + out.extend_from_slice(&data); + std::fs::write(dir.join(shard), out).unwrap(); + } + std::fs::write( + dir.join("model.safetensors.index.json"), + serde_json::to_vec(&serde_json::json!({"weight_map": weight_map})).unwrap(), + ) + .unwrap(); +} + +fn temp(tag: &str) -> PathBuf { + let p = std::env::temp_dir().join(format!("sc629-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&p); + std::fs::create_dir_all(&p).unwrap(); + p +} + +#[test] +fn expert_store_reads_equal_the_resident_loader_bytes() { + let ck = temp("ckpt"); + let st = temp("store"); + write_checkpoint(&ck); + let shape = Qwen3MoeExperts { + model_digest: MODEL, + hidden: H as u64, + moe_intermediate: I as u64, + experts: EXPERTS, + }; + let mut store = ExpertStore::open(&st, StoreLimits::default()).unwrap(); + let mut ckpt = Checkpoint::open(&ck).unwrap(); + index_qwen3_moe(&mut ckpt, &shape, 0..LAYERS, &mut store).unwrap(); + + let reader = ReadAdapter::new( + Arc::new(store.file_source(IoMode::Buffered)), + ReadLimits::default(), + ) + .unwrap(); + let mut resident = ShardSource::open(&ck).unwrap(); + let mut checked = 0; + // A scattered order: each read touches one expert only. + for (l, e) in [(1u32, 3u32), (0, 0), (1, 0), (0, 2), (1, 1), (0, 3)] { + for p in Projection::ALL { + let key = ExpertKey { + model_digest: MODEL, + layer: l, + expert: e, + projection: p, + quant: QuantFormat::Fp8E4m3Block128, + }; + let entry = store.get(&key).expect("indexed"); + let buf = StagingBuffer::new(entry.object_len as usize).unwrap(); + reader + .submit(entry, buf, Instant::now() + Duration::from_secs(30)) + .unwrap(); + let Outcome::Ready(ready) = reader.wait(Duration::from_secs(10)).unwrap().outcome + else { + panic!("read of {key:?} did not verify"); + }; + let (r, c) = dims(p); + let base = format!("model.layers.{l}.mlp.experts.{e}.{}", p.checkpoint_name()); + let mut w = vec![0u8; r * c]; + resident + .read_into(&format!("{base}.weight"), "F8_E4M3", &[r, c], &mut w) + .unwrap(); + let sshape = [r.div_ceil(128), c.div_ceil(128)]; + let mut s = vec![0u8; sshape[0] * sshape[1] * 2]; + resident + .read_into(&format!("{base}.weight_scale_inv"), "BF16", &sshape, &mut s) + .unwrap(); + assert_eq!(ready.weights(), &w[..], "weights {key:?}"); + assert_eq!(ready.scales(), &s[..], "scales {key:?}"); + checked += 1; + } + } + assert_eq!(checked, 18); + let _ = std::fs::remove_dir_all(&ck); + let _ = std::fs::remove_dir_all(&st); +}