diff --git a/.crumb b/.crumb index 8bf031ee..cd134298 100644 --- a/.crumb +++ b/.crumb @@ -119,14 +119,14 @@ } ], "children_root": "sha256:31b31d0c22430a2b7dbaf536741c122daa8e98b3e30440b78e6f0b153415c048", - "compiled_at": "2026-10-30T03:27:35Z", + "compiled_at": "2026-10-30T03:31:20Z", "compiler": "crumb-compile/1", - "digest": "sha256:c546eec7ef8f8fef9070c73dea09205848a64ea17296ef307deb6292061a0bd3", + "digest": "sha256:e8cfbc04962478acaeb5310dda852c1eec42df0e01fe6992d429f951aeff874e", "evidence_files": 3586, "evidence_root": "sha256:ee29710af304de14c30917f3cc8eb87c5b5e9a42b75dd9d009e842279d8075d0", - "files": 8055, - "generated_at_commit": "b20182607e07391024e4e9cacca4868d88390d5a", - "source_tree": "sha256:8f6b80fbe5362465a296d871241c322de5654f35e698f02b35745a3ff9db2ebf" + "files": 8063, + "generated_at_commit": "3a8096cd7899714bcb48d2f56f7076bf4517c17d", + "source_tree": "sha256:f2d3a8e0d1f0284e9495a04dcb0724077847f81503ee2b03bb793299fa68d16e" } }, "history": [], diff --git a/Cargo.lock b/Cargo.lock index 8ca9b953..04404119 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -167,6 +167,10 @@ dependencies = [ "uuid", ] +[[package]] +name = "aien-expert-residency" +version = "0.1.0" + [[package]] name = "aien-expert-store" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 27e37904..03732c2c 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-residency", "crates/aien-expert-store", "crates/aien-scheduler", "crates/aien-security", diff --git a/crates/aien-expert-residency/Cargo.toml b/crates/aien-expert-residency/Cargo.toml new file mode 100644 index 00000000..cdd3ef71 --- /dev/null +++ b/crates/aien-expert-residency/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "aien-expert-residency" +version.workspace = true +edition.workspace = true +license.workspace = true +authors.workspace = true +repository.workspace = true +description = "Bounded host-side MoE expert residency manager: memory ledger, admission, pins, LRU eviction and typed refusals (RIBBON P2, sc#630)" + +[dependencies] diff --git a/crates/aien-expert-residency/src/budget.rs b/crates/aien-expert-residency/src/budget.rs new file mode 100644 index 00000000..ec960e33 --- /dev/null +++ b/crates/aien-expert-residency/src/budget.rs @@ -0,0 +1,198 @@ +//! The memory ledger: fixed reservations first, expert slots from what is +//! left. +//! +//! The plan is computed once and does not change while the manager runs, so +//! the committed total is also the high-water mark of the plan. Live usage +//! (resident and in-flight bytes) is tracked by the manager and is always at +//! or below the corresponding reservation. + +use crate::error::BudgetError; + +/// Shape of the model attention KV cache at the configured maximum context. +/// This is the persisted-attention KV, a different object from expert +/// weights; it is budgeted here only so expert slots cannot eat into it. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct KvShape { + pub layers: u32, + pub kv_heads: u32, + pub head_dim: u32, + pub bytes_per_element: u32, + pub max_context_tokens: u32, + pub max_sequences: u32, +} + +impl KvShape { + /// Bytes for K and V of every layer, KV head, position and sequence. + pub fn bytes(&self) -> Result { + [ + 2, + u64::from(self.layers), + u64::from(self.kv_heads), + u64::from(self.head_dim), + u64::from(self.bytes_per_element), + u64::from(self.max_context_tokens), + u64::from(self.max_sequences), + ] + .iter() + .try_fold(1u64, |acc, &f| acc.checked_mul(f)) + .ok_or(BudgetError::Overflow { what: "kv cache" }) + } +} + +/// What the machine has and what must be set aside before any expert slot. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct MemoryBudget { + /// Total unified memory the plan may describe. + pub total_bytes: u64, + /// OS, driver and resource-manager safety headroom. Never allocated. + pub safety_headroom_bytes: u64, + /// Resident non-expert weights (embeddings, attention, norms, router, + /// any experts kept permanently resident outside the cache). + pub non_expert_weight_bytes: u64, + /// Attention KV cache shape. + pub kv: KvShape, + /// Activations and kernel workspace. + pub scratch_bytes: u64, + /// NVMe read staging buffers. Bytes in flight are charged here. + pub staging_bytes: u64, +} + +/// A ledger category. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum Category { + SafetyHeadroom, + NonExpertWeights, + KvCache, + Scratch, + Staging, + ExpertPool, +} + +/// The computed plan. Every byte of `total_bytes` is in exactly one field: +/// the five reservations, the expert pool or `unassigned_bytes`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Ledger { + pub total_bytes: u64, + pub safety_headroom_bytes: u64, + pub non_expert_weight_bytes: u64, + pub kv_cache_bytes: u64, + pub scratch_bytes: u64, + pub staging_bytes: u64, + pub slot_bytes: u64, + pub slot_count: u32, + /// `slot_count * slot_bytes`. + pub expert_pool_bytes: u64, + /// Left over: less than one slot, or above `max_slots`. Not allocated. + pub unassigned_bytes: u64, +} + +/// What the runtime actually allocated, per category (from the allocator or +/// the driver's report). +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct AllocationReport { + pub non_expert_weight_bytes: u64, + pub kv_cache_bytes: u64, + pub scratch_bytes: u64, + pub staging_bytes: u64, + pub expert_pool_bytes: u64, +} + +impl Ledger { + /// Reserve the fixed categories, then cut the remainder into whole slots + /// of `slot_bytes`, at most `max_slots` of them. + pub fn plan( + budget: &MemoryBudget, + slot_bytes: u64, + max_slots: Option, + ) -> Result { + if slot_bytes == 0 { + return Err(BudgetError::ZeroSlotBytes); + } + let kv_cache_bytes = budget.kv.bytes()?; + let required = [ + budget.safety_headroom_bytes, + budget.non_expert_weight_bytes, + kv_cache_bytes, + budget.scratch_bytes, + budget.staging_bytes, + ] + .iter() + .try_fold(0u64, |acc, &b| acc.checked_add(b)) + .ok_or(BudgetError::Overflow { + what: "fixed reservations", + })?; + if required > budget.total_bytes { + return Err(BudgetError::Oversubscribed { + required, + total: budget.total_bytes, + }); + } + let available = budget.total_bytes - required; + let fit = available / slot_bytes; + let mut slot_count = u32::try_from(fit).unwrap_or(u32::MAX); + if let Some(cap) = max_slots { + slot_count = slot_count.min(cap); + } + if slot_count == 0 { + return Err(BudgetError::NoExpertSlots { + available_bytes: available, + slot_bytes, + }); + } + // Cannot overflow: slot_count * slot_bytes <= available. + let expert_pool_bytes = u64::from(slot_count) * slot_bytes; + Ok(Self { + total_bytes: budget.total_bytes, + safety_headroom_bytes: budget.safety_headroom_bytes, + non_expert_weight_bytes: budget.non_expert_weight_bytes, + kv_cache_bytes, + scratch_bytes: budget.scratch_bytes, + staging_bytes: budget.staging_bytes, + slot_bytes, + slot_count, + expert_pool_bytes, + unassigned_bytes: available - expert_pool_bytes, + }) + } + + /// Everything reserved, including the expert pool. Excludes only + /// `unassigned_bytes`. Fixed for the life of the plan. + pub fn committed_bytes(&self) -> u64 { + self.total_bytes - self.unassigned_bytes + } + + /// The reservation for one category. + pub fn reserved(&self, category: Category) -> u64 { + match category { + Category::SafetyHeadroom => self.safety_headroom_bytes, + Category::NonExpertWeights => self.non_expert_weight_bytes, + Category::KvCache => self.kv_cache_bytes, + Category::Scratch => self.scratch_bytes, + Category::Staging => self.staging_bytes, + Category::ExpertPool => self.expert_pool_bytes, + } + } + + /// Check a real allocation report against the plan. Every category must + /// be at or below its reservation; the first one over is returned. + pub fn check_allocations(&self, report: &AllocationReport) -> Result<(), BudgetError> { + let rows = [ + (Category::NonExpertWeights, report.non_expert_weight_bytes), + (Category::KvCache, report.kv_cache_bytes), + (Category::Scratch, report.scratch_bytes), + (Category::Staging, report.staging_bytes), + (Category::ExpertPool, report.expert_pool_bytes), + ]; + for (category, actual) in rows { + let reserved = self.reserved(category); + if actual > reserved { + return Err(BudgetError::AllocationExceedsReservation { + category, + reserved, + actual, + }); + } + } + Ok(()) + } +} diff --git a/crates/aien-expert-residency/src/error.rs b/crates/aien-expert-residency/src/error.rs new file mode 100644 index 00000000..0ac1694c --- /dev/null +++ b/crates/aien-expert-residency/src/error.rs @@ -0,0 +1,203 @@ +//! Typed errors. Configuration and ledger problems are [`BudgetError`]; +//! everything the manager refuses at run time is a [`Refusal`]. + +use core::fmt; + +use crate::budget::Category; +use crate::manager::{Phase, SlotId}; + +/// The memory plan or an allocation report does not fit. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum BudgetError { + /// A size computation overflowed `u64`. + Overflow { what: &'static str }, + /// The fixed reservations alone exceed the total memory. + Oversubscribed { required: u64, total: u64 }, + /// `slot_bytes` is zero. + ZeroSlotBytes, + /// After the fixed reservations no whole expert slot fits. + NoExpertSlots { + available_bytes: u64, + slot_bytes: u64, + }, + /// `max_in_flight` is zero, so no fetch could ever start. + ZeroInFlight, + /// The in-flight byte limit is larger than the staging reservation. + InFlightBytesExceedStaging { + max_in_flight_bytes: u64, + staging_bytes: u64, + }, + /// The in-flight byte limit is smaller than one slot, so a full-size + /// expert could never be fetched. + InFlightBytesBelowSlot { + max_in_flight_bytes: u64, + slot_bytes: u64, + }, + /// A reported allocation is larger than the ledger reserved for it. + AllocationExceedsReservation { + category: Category, + reserved: u64, + actual: u64, + }, +} + +impl fmt::Display for BudgetError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Overflow { what } => write!(f, "size overflow computing {what}"), + Self::Oversubscribed { required, total } => write!( + f, + "fixed reservations need {required} bytes but only {total} exist" + ), + Self::ZeroSlotBytes => write!(f, "slot size is zero"), + Self::NoExpertSlots { + available_bytes, + slot_bytes, + } => write!( + f, + "{available_bytes} bytes left after reservations, less than one {slot_bytes}-byte slot" + ), + Self::ZeroInFlight => write!(f, "max_in_flight is zero"), + Self::InFlightBytesExceedStaging { + max_in_flight_bytes, + staging_bytes, + } => write!( + f, + "in-flight limit {max_in_flight_bytes} exceeds staging reservation {staging_bytes}" + ), + Self::InFlightBytesBelowSlot { + max_in_flight_bytes, + slot_bytes, + } => write!( + f, + "in-flight limit {max_in_flight_bytes} is below one slot of {slot_bytes} bytes" + ), + Self::AllocationExceedsReservation { + category, + reserved, + actual, + } => write!( + f, + "{category:?} allocation {actual} exceeds its reservation {reserved}" + ), + } + } +} + +impl std::error::Error for BudgetError {} + +/// Why a fetch did not reach `Ready`. Reported by the caller. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum FailureCause { + /// The NVMe read failed, was short or timed out. + Read, + /// The bytes did not match the content address. + DigestMismatch, + /// The staging-to-slot copy failed. + Copy, + /// The GPU visibility fence failed or timed out. + GpuFence, + /// The fetch was cancelled. + Cancelled, +} + +/// A run-time refusal. Nothing is changed when one is returned, except the +/// refusal counter. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Refusal { + /// Every slot is pinned or in flight; nothing can be evicted. + PinnedExhaustion { + slots: u32, + pinned: u32, + in_flight: u32, + }, + /// The number of fetches in flight is at its limit (backpressure). + InFlightLimit { limit: u32 }, + /// Starting this fetch would exceed the in-flight byte limit. + InFlightBytesLimit { + in_flight_bytes: u64, + requested: u64, + limit: u64, + }, + /// The object does not fit one slot. + ObjectTooLarge { bytes: u64, slot_bytes: u64 }, + /// A zero-byte object was requested. + ZeroSizedObject, + /// The key is already admitted with a different size. + SizeMismatch { admitted: u64, requested: u64 }, + /// The ticket refers to a slot generation that no longer exists. + StaleTicket { slot: SlotId, generation: u64 }, + /// The pin refers to a slot generation that no longer exists. + StalePin { slot: SlotId, generation: u64 }, + /// The step is not allowed from the entry's current phase. + WrongPhase { + slot: SlotId, + expected: Phase, + found: Phase, + }, + /// The pin count of one entry would overflow `u32`. + PinOverflow { slot: SlotId }, + /// The fetch behind this pin failed; the expert is not resident. + FetchFailed { + slot: SlotId, + generation: u64, + cause: FailureCause, + }, +} + +impl fmt::Display for Refusal { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::PinnedExhaustion { + slots, + pinned, + in_flight, + } => write!( + f, + "all {slots} slots busy ({pinned} pinned, {in_flight} in flight)" + ), + Self::InFlightLimit { limit } => write!(f, "{limit} fetches already in flight"), + Self::InFlightBytesLimit { + in_flight_bytes, + requested, + limit, + } => write!( + f, + "{in_flight_bytes} bytes in flight + {requested} would exceed {limit}" + ), + Self::ObjectTooLarge { bytes, slot_bytes } => { + write!(f, "object of {bytes} bytes exceeds slot size {slot_bytes}") + } + Self::ZeroSizedObject => write!(f, "zero-sized object"), + Self::SizeMismatch { + admitted, + requested, + } => write!( + f, + "key admitted with {admitted} bytes, requested with {requested}" + ), + Self::StaleTicket { slot, generation } => { + write!(f, "stale ticket for slot {slot} generation {generation}") + } + Self::StalePin { slot, generation } => { + write!(f, "stale pin for slot {slot} generation {generation}") + } + Self::WrongPhase { + slot, + expected, + found, + } => write!(f, "slot {slot}: expected {expected:?}, found {found:?}"), + Self::PinOverflow { slot } => write!(f, "slot {slot}: pin count overflow"), + Self::FetchFailed { + slot, + generation, + cause, + } => write!( + f, + "fetch for slot {slot} generation {generation} failed: {cause:?}" + ), + } + } +} + +impl std::error::Error for Refusal {} diff --git a/crates/aien-expert-residency/src/lib.rs b/crates/aien-expert-residency/src/lib.rs new file mode 100644 index 00000000..796f6760 --- /dev/null +++ b/crates/aien-expert-residency/src/lib.rs @@ -0,0 +1,34 @@ +//! Omega Expert Ribbon P2 (sc#630): the bounded host-side expert residency +//! manager. +//! +//! This crate is the cache policy and correctness state machine only. It +//! hands out slot numbers and generations; it never touches GPU pointers, +//! NVMe devices or decode. The caller (the read adapter of sc#629, the +//! versioned GPU slots of omega#533, wiring in sc#632) drives the transfers +//! and reports each step back. +//! +//! * [`budget`]: the memory ledger. OS / resource-manager headroom, +//! non-expert weights, the model KV cache at the configured maximum context, +//! scratch and staging are reserved first; only what is left becomes fixed +//! expert slots. Oversubscription is refused, never assumed away. +//! * [`manager`]: the residency state machine. One expert identity maps to +//! one slot and one generation. States run +//! `Absent -> Fetching -> Verified -> Copying -> Ready -> InUse -> Evictable`, +//! and a failure is explicit. A pinned slot is never evicted. Eviction is +//! least recently used with a deterministic logical clock. Every refusal is +//! a typed [`Refusal`]. +//! +//! Correctness rule (aienix#4 invariant 1): a miss either waits for the exact +//! expert the router selected or fails explicitly. This crate has no notion of +//! a substitute expert, a dropped expert or a lower-precision fallback. + +pub mod budget; +pub mod error; +pub mod manager; + +pub use budget::{AllocationReport, Category, KvShape, Ledger, MemoryBudget}; +pub use error::{BudgetError, FailureCause, Refusal}; +pub use manager::{ + Acquired, ExpertIdentity, ExpertPart, ExpertState, FetchTicket, Phase, Pin, PinStatus, + ResidencyConfig, ResidencyManager, SlotId, Stats, +}; diff --git a/crates/aien-expert-residency/src/manager.rs b/crates/aien-expert-residency/src/manager.rs new file mode 100644 index 00000000..7b2aa6b1 --- /dev/null +++ b/crates/aien-expert-residency/src/manager.rs @@ -0,0 +1,729 @@ +//! The residency state machine. +//! +//! ## Lifecycle +//! +//! ```text +//! Absent --acquire (miss)--> Fetching --mark_verified--> Verified +//! --mark_copying--> Copying --publish--> Ready +//! Ready --pin--> InUse --last release--> Evictable --evict--> Absent +//! Fetching | Verified | Copying --fail--> Failed (held until the last pin +//! is released) --> Absent +//! ``` +//! +//! `publish` must be called only after the transfer completed, the digest +//! matched and the GPU visibility fence signalled (aienix#4 invariant 3). +//! +//! ## Pins +//! +//! [`ResidencyManager::acquire`] always returns a [`Pin`], also on a miss: a +//! request pins its experts from the moment the router selects them until +//! its GPU read fence has passed, then releases each pin. An entry with any +//! pin, or with a fetch in flight, is never evicted. A [`Pin`] is not +//! `Clone`, so it can be released only once. +//! +//! ## Generations (ABA) +//! +//! Every admission gets a fresh generation from one counter that never +//! repeats. Pins and tickets carry `(slot, generation)`; after a slot is +//! reused, an old pin or ticket is refused as stale instead of acting on the +//! new occupant. +//! +//! ## Eviction order +//! +//! Least recently used, by a logical clock that advances on every acquire +//! and release. Ticks are unique, so the order is total and deterministic for +//! a given sequence of calls. Free slots are reused lowest index first. + +use std::collections::{BTreeMap, BTreeSet}; +use std::fmt::Debug; + +use crate::budget::{Ledger, MemoryBudget}; +use crate::error::{BudgetError, FailureCause, Refusal}; + +/// Index of a fixed logical expert slot. +pub type SlotId = u32; + +/// Which part of an expert's MLP an identity names. `GateUp` is for +/// checkpoints that store gate and up fused. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum ExpertPart { + Gate, + Up, + GateUp, + Down, +} + +/// A stable expert identity: checkpoint digest, layer, expert, part. The +/// manager is generic over the key, so the sc#629 store key (which also +/// carries the quantization format) can be used directly instead. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct ExpertIdentity { + pub checkpoint_digest: [u8; 32], + pub layer: u32, + pub expert: u32, + pub part: ExpertPart, +} + +/// Internal phase of an admitted entry. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Phase { + Fetching, + Verified, + Copying, + Ready, + /// The fetch failed; the slot is held only until its pins are released. + Failed(FailureCause), +} + +/// Externally visible state of an expert identity. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ExpertState { + Absent, + Fetching, + Verified, + Copying, + /// Published and not pinned, not yet used since publish. + Ready, + /// Published and pinned by at least one request. + InUse, + /// Published, not pinned, used at least once. + Evictable, +} + +/// What a pin holder sees when it polls. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum PinStatus { + /// The expert is resident and published in this slot generation. + Ready, + /// Still in flight; the holder must wait (never substitute). + Waiting(Phase), +} + +/// A request's hold on one expert. Not `Clone`: release it exactly once. +#[derive(Debug, PartialEq, Eq)] +#[must_use = "a pin must be released, or the slot stays pinned"] +pub struct Pin { + slot: SlotId, + generation: u64, +} + +impl Pin { + pub fn slot(&self) -> SlotId { + self.slot + } + pub fn generation(&self) -> u64 { + self.generation + } +} + +/// The right to drive one fetch through its steps. Handed to exactly one +/// caller, the one whose acquire missed. +#[derive(Debug, PartialEq, Eq)] +#[must_use = "a fetch ticket must be published or failed"] +pub struct FetchTicket { + slot: SlotId, + generation: u64, + bytes: u64, +} + +impl FetchTicket { + pub fn slot(&self) -> SlotId { + self.slot + } + pub fn generation(&self) -> u64 { + self.generation + } + pub fn bytes(&self) -> u64 { + self.bytes + } +} + +/// Result of a successful acquire. +#[derive(Debug, PartialEq, Eq)] +pub enum Acquired { + /// Hit: resident and published. + Ready(Pin), + /// Miss: a slot was assigned; the caller must fetch into it. + Fetch(Pin, FetchTicket), + /// Another caller's fetch for the same key is in flight; wait for it. + Pending(Pin), +} + +impl Acquired { + pub fn pin(&self) -> &Pin { + match self { + Self::Ready(p) | Self::Fetch(p, _) | Self::Pending(p) => p, + } + } +} + +/// Configuration of one manager. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ResidencyConfig { + pub budget: MemoryBudget, + /// Size of one fixed expert slot. Every admitted object must fit. + pub slot_bytes: u64, + /// Optional cap on the number of slots below what the budget allows. + pub max_slots: Option, + /// Maximum fetches in flight (queue depth). + pub max_in_flight: u32, + /// Maximum bytes in flight. Must fit the staging reservation and hold at + /// least one full slot. + pub max_in_flight_bytes: u64, +} + +/// Counters. All monotonic except the `current_*` gauges. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct Stats { + pub hits: u64, + /// Acquires that joined a fetch already in flight. + pub joined: u64, + pub misses: u64, + pub published: u64, + pub evictions: u64, + pub failures: u64, + /// Fresh fetches rolled back by [`ResidencyManager::acquire_all`]. + pub rolled_back: u64, + pub refusals: u64, + pub current_in_flight: u32, + pub current_in_flight_bytes: u64, + pub peak_in_flight_bytes: u64, + pub current_resident_bytes: u64, + pub peak_resident_bytes: u64, + pub current_pins: u64, + /// Sum and maximum of admit-to-publish time, from caller timestamps. + pub fetch_wait_ns_total: u64, + pub fetch_wait_ns_max: u64, +} + +#[derive(Debug, Clone)] +struct Entry { + key: K, + generation: u64, + phase: Phase, + pins: u32, + bytes: u64, + last_use: u64, + used: bool, + admitted_ns: u64, +} + +impl Entry { + fn in_flight(&self) -> bool { + matches!( + self.phase, + Phase::Fetching | Phase::Verified | Phase::Copying + ) + } + fn evictable(&self) -> bool { + self.phase == Phase::Ready && self.pins == 0 + } +} + +/// The bounded residency manager. +#[derive(Debug)] +pub struct ResidencyManager { + ledger: Ledger, + max_in_flight: u32, + max_in_flight_bytes: u64, + slots: Vec>>, + index: BTreeMap, + free: BTreeSet, + clock: u64, + next_generation: u64, + stats: Stats, +} + +impl ResidencyManager { + /// Plan the ledger and create an empty manager. Fails closed on any + /// oversubscription or inconsistent limit. + pub fn new(config: ResidencyConfig) -> Result { + let ledger = Ledger::plan(&config.budget, config.slot_bytes, config.max_slots)?; + if config.max_in_flight == 0 { + return Err(BudgetError::ZeroInFlight); + } + if config.max_in_flight_bytes > ledger.staging_bytes { + return Err(BudgetError::InFlightBytesExceedStaging { + max_in_flight_bytes: config.max_in_flight_bytes, + staging_bytes: ledger.staging_bytes, + }); + } + if config.max_in_flight_bytes < config.slot_bytes { + return Err(BudgetError::InFlightBytesBelowSlot { + max_in_flight_bytes: config.max_in_flight_bytes, + slot_bytes: config.slot_bytes, + }); + } + let n = ledger.slot_count; + Ok(Self { + ledger, + max_in_flight: config.max_in_flight, + max_in_flight_bytes: config.max_in_flight_bytes, + slots: (0..n).map(|_| None).collect(), + index: BTreeMap::new(), + free: (0..n).collect(), + clock: 0, + next_generation: 1, + stats: Stats::default(), + }) + } + + pub fn ledger(&self) -> &Ledger { + &self.ledger + } + + pub fn stats(&self) -> Stats { + self.stats + } + + pub fn slot_count(&self) -> u32 { + self.ledger.slot_count + } + + /// The state of one identity. + pub fn state(&self, key: &K) -> ExpertState { + let Some(&slot) = self.index.get(key) else { + return ExpertState::Absent; + }; + let e = self.entry(slot); + match e.phase { + Phase::Fetching => ExpertState::Fetching, + Phase::Verified => ExpertState::Verified, + Phase::Copying => ExpertState::Copying, + Phase::Ready if e.pins > 0 => ExpertState::InUse, + Phase::Ready if e.used => ExpertState::Evictable, + Phase::Ready => ExpertState::Ready, + // Failed entries are removed from the index. + Phase::Failed(_) => ExpertState::Absent, + } + } + + /// The slot and generation currently holding `key`, if admitted. + pub fn slot_of(&self, key: &K) -> Option<(SlotId, u64)> { + self.index.get(key).map(|&s| (s, self.entry(s).generation)) + } + + /// Pin `key` of `bytes` bytes. On a hit the pin is ready; on a miss a + /// slot is assigned (evicting the least recently used unpinned resident + /// entry if no slot is free) and the caller gets the fetch ticket. + /// `now_ns` is the caller's monotonic clock, used only for wait counters. + pub fn acquire(&mut self, key: K, bytes: u64, now_ns: u64) -> Result { + let r = self.acquire_inner(key, bytes, now_ns); + if r.is_err() { + self.stats.refusals += 1; + } + r + } + + fn acquire_inner(&mut self, key: K, bytes: u64, now_ns: u64) -> Result { + if let Some(&slot) = self.index.get(&key) { + let e = self.entry(slot); + if e.bytes != bytes { + return Err(Refusal::SizeMismatch { + admitted: e.bytes, + requested: bytes, + }); + } + let pins = e.pins.checked_add(1).ok_or(Refusal::PinOverflow { slot })?; + let tick = self.tick(); + let e = self.slots[slot as usize].as_mut().expect("indexed slot"); + e.pins = pins; + e.last_use = tick; + let pin = Pin { + slot, + generation: e.generation, + }; + let ready = e.phase == Phase::Ready; + self.stats.current_pins += 1; + return Ok(if ready { + self.stats.hits += 1; + Acquired::Ready(pin) + } else { + self.stats.joined += 1; + Acquired::Pending(pin) + }); + } + + // Miss: validate everything before evicting anything. + if bytes == 0 { + return Err(Refusal::ZeroSizedObject); + } + if bytes > self.ledger.slot_bytes { + return Err(Refusal::ObjectTooLarge { + bytes, + slot_bytes: self.ledger.slot_bytes, + }); + } + if self.stats.current_in_flight >= self.max_in_flight { + return Err(Refusal::InFlightLimit { + limit: self.max_in_flight, + }); + } + let in_flight_bytes = self.stats.current_in_flight_bytes; + if in_flight_bytes + bytes > self.max_in_flight_bytes { + return Err(Refusal::InFlightBytesLimit { + in_flight_bytes, + requested: bytes, + limit: self.max_in_flight_bytes, + }); + } + let slot = match self.free.first().copied() { + Some(s) => { + self.free.remove(&s); + s + } + None => { + let victim = self.lru_victim().ok_or_else(|| self.exhaustion())?; + self.evict(victim); + victim + } + }; + + let tick = self.tick(); + let generation = self.next_generation; + self.next_generation += 1; + self.slots[slot as usize] = Some(Entry { + key: key.clone(), + generation, + phase: Phase::Fetching, + pins: 1, + bytes, + last_use: tick, + used: false, + admitted_ns: now_ns, + }); + self.index.insert(key, slot); + self.stats.misses += 1; + self.stats.current_pins += 1; + self.stats.current_in_flight += 1; + self.stats.current_in_flight_bytes += bytes; + self.stats.peak_in_flight_bytes = self + .stats + .peak_in_flight_bytes + .max(self.stats.current_in_flight_bytes); + Ok(Acquired::Fetch( + Pin { slot, generation }, + FetchTicket { + slot, + generation, + bytes, + }, + )) + } + + /// Acquire every key of one request, or none. Keys may repeat (each + /// occurrence takes its own pin). On a refusal every pin taken by this + /// call is released and every fetch it started is rolled back, then the + /// refusal is returned. Entries evicted to make room stay evicted. + pub fn acquire_all( + &mut self, + keys: &[(K, u64)], + now_ns: u64, + ) -> Result, Refusal> { + let mut taken: Vec = Vec::with_capacity(keys.len()); + for (key, bytes) in keys { + match self.acquire(key.clone(), *bytes, now_ns) { + Ok(a) => taken.push(a), + Err(refusal) => { + // Release in reverse so fresh fetches lose their last + // pin before being rolled back. + while let Some(a) = taken.pop() { + self.rollback(a); + } + return Err(refusal); + } + } + } + Ok(taken) + } + + fn rollback(&mut self, a: Acquired) { + match a { + Acquired::Ready(pin) | Acquired::Pending(pin) => { + self.release(pin).expect("pin taken by this call"); + } + Acquired::Fetch(pin, ticket) => { + self.release(pin).expect("pin taken by this call"); + let slot = ticket.slot; + let e = self.entry(slot); + debug_assert!(e.generation == ticket.generation && e.phase == Phase::Fetching); + // Pins are released newest first, so every later duplicate of + // this key (which joined this fetch) is already released. + assert_eq!(e.pins, 0, "fresh fetch still pinned during rollback"); + self.finish_in_flight(slot); + let e = self.slots[slot as usize].take().expect("slot"); + self.index.remove(&e.key); + self.free.insert(slot); + self.stats.rolled_back += 1; + } + } + } + + /// Fetching -> Verified: the bytes are in staging and the digest matched. + pub fn mark_verified(&mut self, ticket: &FetchTicket) -> Result<(), Refusal> { + self.step(ticket, Phase::Fetching, Phase::Verified) + } + + /// Verified -> Copying: the staging-to-slot copy has started. + pub fn mark_copying(&mut self, ticket: &FetchTicket) -> Result<(), Refusal> { + self.step(ticket, Phase::Verified, Phase::Copying) + } + + /// Copying -> Ready. Call only after the copy completed and the GPU + /// visibility fence signalled. + pub fn publish(&mut self, ticket: &FetchTicket, now_ns: u64) -> Result<(), Refusal> { + self.step(ticket, Phase::Copying, Phase::Ready)?; + let slot = ticket.slot; + let (bytes, admitted_ns) = { + let e = self.entry(slot); + (e.bytes, e.admitted_ns) + }; + self.finish_in_flight(slot); + let wait = now_ns.saturating_sub(admitted_ns); + let s = &mut self.stats; + s.published += 1; + s.current_resident_bytes += bytes; + s.peak_resident_bytes = s.peak_resident_bytes.max(s.current_resident_bytes); + s.fetch_wait_ns_total = s.fetch_wait_ns_total.saturating_add(wait); + s.fetch_wait_ns_max = s.fetch_wait_ns_max.max(wait); + Ok(()) + } + + /// Any in-flight phase -> Failed. The key is unmapped at once, so the + /// next acquire starts a clean fetch; pin holders see + /// [`Refusal::FetchFailed`] when they poll and must release. + pub fn fail(&mut self, ticket: &FetchTicket, cause: FailureCause) -> Result<(), Refusal> { + let slot = self.check_ticket(ticket)?; + let e = self.entry(slot); + if !e.in_flight() { + return Err(Refusal::WrongPhase { + slot, + expected: Phase::Fetching, + found: e.phase, + }); + } + self.finish_in_flight(slot); + self.stats.failures += 1; + let e = self.slots[slot as usize].as_mut().expect("slot"); + e.phase = Phase::Failed(cause); + let key = e.key.clone(); + let pins = e.pins; + self.index.remove(&key); + if pins == 0 { + self.slots[slot as usize] = None; + self.free.insert(slot); + } + Ok(()) + } + + /// The current phase of the fetch behind `ticket`. A ticket whose slot + /// generation is gone (failed and freed, or evicted after publish) is + /// refused as stale. + pub fn ticket_phase(&self, ticket: &FetchTicket) -> Result { + let slot = self.check_ticket(ticket)?; + Ok(self.entry(slot).phase) + } + + /// Where the pinned expert stands. + pub fn poll(&self, pin: &Pin) -> Result { + let e = self.pinned_entry(pin)?; + match e.phase { + Phase::Ready => Ok(PinStatus::Ready), + Phase::Failed(cause) => Err(Refusal::FetchFailed { + slot: pin.slot, + generation: pin.generation, + cause, + }), + p => Ok(PinStatus::Waiting(p)), + } + } + + /// Drop one pin. Call after the GPU read fence of the request has + /// passed. The slot becomes evictable when its last pin goes. + pub fn release(&mut self, pin: Pin) -> Result<(), Refusal> { + self.pinned_entry(&pin)?; + let tick = self.tick(); + let slot = pin.slot; + let e = self.slots[slot as usize].as_mut().expect("slot"); + e.pins -= 1; + e.last_use = tick; + if e.phase == Phase::Ready { + e.used = true; + } + let free_failed = matches!(e.phase, Phase::Failed(_)) && e.pins == 0; + self.stats.current_pins -= 1; + if free_failed { + self.slots[slot as usize] = None; + self.free.insert(slot); + } + Ok(()) + } + + /// The slot that the next miss would evict, if no slot is free. + pub fn next_victim(&self) -> Option { + if self.free.is_empty() { + self.lru_victim() + } else { + None + } + } + + /// Check every internal invariant. For tests and debug assertions. + pub fn check_invariants(&self) -> Result<(), String> { + let mut pins = 0u64; + let mut in_flight = 0u32; + let mut in_flight_bytes = 0u64; + let mut resident = 0u64; + let mut generations = BTreeSet::new(); + for (i, s) in self.slots.iter().enumerate() { + let slot = i as SlotId; + match s { + None => { + if !self.free.contains(&slot) { + return Err(format!("empty slot {slot} not on free list")); + } + } + Some(e) => { + if self.free.contains(&slot) { + return Err(format!("occupied slot {slot} on free list")); + } + if !generations.insert(e.generation) || e.generation >= self.next_generation { + return Err(format!("slot {slot} bad generation {}", e.generation)); + } + if e.bytes == 0 || e.bytes > self.ledger.slot_bytes { + return Err(format!("slot {slot} bad size {}", e.bytes)); + } + pins += u64::from(e.pins); + match e.phase { + Phase::Failed(_) => { + if e.pins == 0 { + return Err(format!("failed slot {slot} held with no pins")); + } + if self.index.get(&e.key) == Some(&slot) { + return Err(format!("failed slot {slot} still indexed")); + } + } + _ => { + if self.index.get(&e.key) != Some(&slot) { + return Err(format!("slot {slot} not indexed by its key")); + } + } + } + if e.in_flight() { + in_flight += 1; + in_flight_bytes += e.bytes; + } + if e.phase == Phase::Ready { + resident += e.bytes; + } + } + } + } + for (k, &slot) in &self.index { + match self.slots.get(slot as usize).and_then(Option::as_ref) { + Some(e) if &e.key == k => {} + _ => return Err(format!("index entry {k:?} -> {slot} dangling")), + } + } + let s = &self.stats; + if pins != s.current_pins { + return Err(format!("pins {pins} != counter {}", s.current_pins)); + } + if in_flight != s.current_in_flight || in_flight_bytes != s.current_in_flight_bytes { + return Err("in-flight counters drifted".into()); + } + if in_flight > self.max_in_flight || in_flight_bytes > self.max_in_flight_bytes { + return Err("in-flight limits exceeded".into()); + } + if resident != s.current_resident_bytes || resident > self.ledger.expert_pool_bytes { + return Err(format!("resident bytes {resident} inconsistent")); + } + if s.peak_in_flight_bytes > self.ledger.staging_bytes + || s.peak_resident_bytes > self.ledger.expert_pool_bytes + { + return Err("high-water mark above reservation".into()); + } + Ok(()) + } + + // ---- internals ---- + + fn tick(&mut self) -> u64 { + self.clock += 1; + self.clock + } + + fn entry(&self, slot: SlotId) -> &Entry { + self.slots[slot as usize].as_ref().expect("occupied slot") + } + + fn lru_victim(&self) -> Option { + self.slots + .iter() + .enumerate() + .filter_map(|(i, s)| { + s.as_ref() + .filter(|e| e.evictable()) + .map(|e| (e.last_use, i)) + }) + .min() + .map(|(_, i)| i as SlotId) + } + + fn exhaustion(&self) -> Refusal { + let pinned = self.slots.iter().flatten().filter(|e| e.pins > 0).count() as u32; + Refusal::PinnedExhaustion { + slots: self.ledger.slot_count, + pinned, + in_flight: self.stats.current_in_flight, + } + } + + fn evict(&mut self, slot: SlotId) { + let e = self.slots[slot as usize].take().expect("victim"); + debug_assert!(e.evictable()); + self.index.remove(&e.key); + self.stats.current_resident_bytes -= e.bytes; + self.stats.evictions += 1; + } + + fn finish_in_flight(&mut self, slot: SlotId) { + let bytes = self.entry(slot).bytes; + self.stats.current_in_flight -= 1; + self.stats.current_in_flight_bytes -= bytes; + } + + fn check_ticket(&self, t: &FetchTicket) -> Result { + match self.slots.get(t.slot as usize).and_then(Option::as_ref) { + Some(e) if e.generation == t.generation => Ok(t.slot), + _ => Err(Refusal::StaleTicket { + slot: t.slot, + generation: t.generation, + }), + } + } + + fn pinned_entry(&self, pin: &Pin) -> Result<&Entry, Refusal> { + match self.slots.get(pin.slot as usize).and_then(Option::as_ref) { + Some(e) if e.generation == pin.generation && e.pins > 0 => Ok(e), + _ => Err(Refusal::StalePin { + slot: pin.slot, + generation: pin.generation, + }), + } + } + + fn step(&mut self, ticket: &FetchTicket, from: Phase, to: Phase) -> Result<(), Refusal> { + let slot = self.check_ticket(ticket)?; + let e = self.slots[slot as usize].as_mut().expect("slot"); + if e.phase != from { + return Err(Refusal::WrongPhase { + slot, + expected: from, + found: e.phase, + }); + } + e.phase = to; + Ok(()) + } +} diff --git a/crates/aien-expert-residency/tests/budget_tests.rs b/crates/aien-expert-residency/tests/budget_tests.rs new file mode 100644 index 00000000..671d8af0 --- /dev/null +++ b/crates/aien-expert-residency/tests/budget_tests.rs @@ -0,0 +1,265 @@ +mod common; + +use aien_expert_residency::{ + AllocationReport, BudgetError, Category, KvShape, Ledger, MemoryBudget, ResidencyConfig, + ResidencyManager, +}; +use common::*; + +const GIB: u64 = 1 << 30; + +/// Qwen3-30B-A3B-like attention shape: 48 layers, 4 KV heads, head dim 128, +/// BF16, 32K context, 1 sequence. +fn qwen_kv(ctx: u32, seqs: u32) -> KvShape { + KvShape { + layers: 48, + kv_heads: 4, + head_dim: 128, + bytes_per_element: 2, + max_context_tokens: ctx, + max_sequences: seqs, + } +} + +fn spark_budget(ctx: u32) -> MemoryBudget { + MemoryBudget { + total_bytes: 128 * GIB, + safety_headroom_bytes: 8 * GIB, + non_expert_weight_bytes: 2 * GIB, + kv: qwen_kv(ctx, 1), + scratch_bytes: 2 * GIB, + staging_bytes: 256 * MIB, + } +} + +#[test] +fn kv_bytes_match_hand_computation() { + // 2 * 48 * 4 * 128 * 2 * 32768 * 1 = 3 GiB. + assert_eq!(qwen_kv(32768, 1).bytes().unwrap(), 3 * GIB); + assert_eq!(qwen_kv(32768, 4).bytes().unwrap(), 12 * GIB); + assert_eq!(kv_none().bytes().unwrap(), 0); +} + +#[test] +fn kv_overflow_is_refused() { + let kv = KvShape { + layers: u32::MAX, + kv_heads: u32::MAX, + head_dim: u32::MAX, + bytes_per_element: u32::MAX, + max_context_tokens: u32::MAX, + max_sequences: u32::MAX, + }; + assert_eq!(kv.bytes(), Err(BudgetError::Overflow { what: "kv cache" })); +} + +#[test] +fn ledger_partitions_total_exactly() { + let slot = 4_718_592; // one Qwen3-30B expert, 3 x 2048 x 768 FP8 + for ctx in [4096, 32768, 65536] { + let b = spark_budget(ctx); + let l = Ledger::plan(&b, slot, None).unwrap(); + let sum = l.safety_headroom_bytes + + l.non_expert_weight_bytes + + l.kv_cache_bytes + + l.scratch_bytes + + l.staging_bytes + + l.expert_pool_bytes + + l.unassigned_bytes; + assert_eq!(sum, b.total_bytes, "ctx {ctx}"); + assert!(l.unassigned_bytes < slot); + assert_eq!(l.expert_pool_bytes, u64::from(l.slot_count) * slot); + assert_eq!(l.committed_bytes() + l.unassigned_bytes, b.total_bytes); + // Never assume all memory can store experts. + assert!(l.expert_pool_bytes <= b.total_bytes - b.safety_headroom_bytes); + } +} + +#[test] +fn longer_context_leaves_fewer_slots() { + let slot = 4_718_592; + let counts: Vec = [4096, 32768, 65536] + .iter() + .map(|&c| { + Ledger::plan(&spark_budget(c), slot, None) + .unwrap() + .slot_count + }) + .collect(); + assert!(counts[0] > counts[1] && counts[1] > counts[2], "{counts:?}"); +} + +#[test] +fn oversubscription_is_refused() { + let mut b = spark_budget(32768); + b.non_expert_weight_bytes = 120 * GIB; + match Ledger::plan(&b, 4096, None) { + Err(BudgetError::Oversubscribed { required, total }) => { + assert!(required > total); + assert_eq!(total, 128 * GIB); + } + other => panic!("{other:?}"), + } +} + +#[test] +fn exactly_full_reservations_leave_no_slot() { + let b = MemoryBudget { + total_bytes: 10_000, + safety_headroom_bytes: 10_000, + non_expert_weight_bytes: 0, + kv: kv_none(), + scratch_bytes: 0, + staging_bytes: 0, + }; + assert_eq!( + Ledger::plan(&b, 1, None), + Err(BudgetError::NoExpertSlots { + available_bytes: 0, + slot_bytes: 1 + }) + ); +} + +#[test] +fn less_than_one_slot_is_refused() { + let b = MemoryBudget { + total_bytes: 10_000, + safety_headroom_bytes: 6_000, + non_expert_weight_bytes: 0, + kv: kv_none(), + scratch_bytes: 0, + staging_bytes: 0, + }; + assert_eq!( + Ledger::plan(&b, 4096, None), + Err(BudgetError::NoExpertSlots { + available_bytes: 4_000, + slot_bytes: 4096 + }) + ); + assert_eq!(Ledger::plan(&b, 0, None), Err(BudgetError::ZeroSlotBytes)); + assert_eq!( + Ledger::plan(&b, 4000, Some(0)).map(|l| l.slot_count), + Err(BudgetError::NoExpertSlots { + available_bytes: 4_000, + slot_bytes: 4000 + }) + ); +} + +#[test] +fn reservation_sum_overflow_is_refused() { + let mut b = spark_budget(4096); + b.safety_headroom_bytes = u64::MAX; + assert_eq!( + Ledger::plan(&b, 4096, None), + Err(BudgetError::Overflow { + what: "fixed reservations" + }) + ); +} + +#[test] +fn max_slots_caps_pool_and_rest_is_unassigned() { + let b = spark_budget(4096); + let l = Ledger::plan(&b, MIB, Some(10)).unwrap(); + assert_eq!(l.slot_count, 10); + assert_eq!(l.expert_pool_bytes, 10 * MIB); + assert!(l.unassigned_bytes > 100 * GIB); +} + +#[test] +fn allocation_report_checked_per_category() { + let l = Ledger::plan(&spark_budget(32768), MIB, Some(100)).unwrap(); + let ok = AllocationReport { + non_expert_weight_bytes: 2 * GIB, + kv_cache_bytes: 3 * GIB, + scratch_bytes: GIB, + staging_bytes: 256 * MIB, + expert_pool_bytes: 100 * MIB, + }; + assert_eq!(l.check_allocations(&ok), Ok(())); + let over = AllocationReport { + kv_cache_bytes: 3 * GIB + 1, + ..ok + }; + assert_eq!( + l.check_allocations(&over), + Err(BudgetError::AllocationExceedsReservation { + category: Category::KvCache, + reserved: 3 * GIB, + actual: 3 * GIB + 1 + }) + ); + let pool_over = AllocationReport { + expert_pool_bytes: 100 * MIB + 1, + ..ok + }; + assert!(matches!( + l.check_allocations(&pool_over), + Err(BudgetError::AllocationExceedsReservation { + category: Category::ExpertPool, + .. + }) + )); +} + +#[test] +fn manager_config_limits_are_validated() { + let mut c = config(4, 2, 2 * SLOT); + c.max_in_flight = 0; + assert_eq!( + ResidencyManager::::new(c).err(), + Some(BudgetError::ZeroInFlight) + ); + let mut c = config(4, 2, 2 * SLOT); + c.max_in_flight_bytes = 3 * SLOT; + assert_eq!( + ResidencyManager::::new(c).err(), + Some(BudgetError::InFlightBytesExceedStaging { + max_in_flight_bytes: 3 * SLOT, + staging_bytes: 2 * SLOT + }) + ); + let mut c = config(4, 2, 2 * SLOT); + c.max_in_flight_bytes = SLOT - 1; + assert_eq!( + ResidencyManager::::new(c).err(), + Some(BudgetError::InFlightBytesBelowSlot { + max_in_flight_bytes: SLOT - 1, + slot_bytes: SLOT + }) + ); +} + +/// High-water marks stay within their reservations and are stable: running +/// the same workload twice more does not raise them past the first plateau. +#[test] +fn high_water_is_bounded_and_stable_at_varied_cache_sizes() { + for slots in [1u32, 2, 3, 8, 33] { + let c: ResidencyConfig = config(slots, 2, 2 * SLOT); + let mut m = ResidencyManager::new(c).unwrap(); + let mut rng = Rng(0x9E37_79B9 ^ u64::from(slots)); + let mut run = |m: &mut ResidencyManager<_>| { + for _ in 0..500 { + let k = id(rng.below(4) as u32, rng.below(16) as u32); + touch(m, k); + } + }; + run(&mut m); + let first = m.stats(); + run(&mut m); + run(&mut m); + let s = m.stats(); + assert_eq!( + s.peak_resident_bytes, first.peak_resident_bytes, + "slots {slots}" + ); + assert_eq!(s.peak_in_flight_bytes, first.peak_in_flight_bytes); + assert!(s.peak_resident_bytes <= m.ledger().expert_pool_bytes); + assert!(s.peak_in_flight_bytes <= m.ledger().staging_bytes); + assert_eq!(s.peak_resident_bytes, u64::from(slots.min(64)) * SLOT); + m.check_invariants().unwrap(); + } +} diff --git a/crates/aien-expert-residency/tests/common/mod.rs b/crates/aien-expert-residency/tests/common/mod.rs new file mode 100644 index 00000000..a8df88e9 --- /dev/null +++ b/crates/aien-expert-residency/tests/common/mod.rs @@ -0,0 +1,94 @@ +#![allow(dead_code)] + +use aien_expert_residency::{ + Acquired, ExpertIdentity, ExpertPart, FetchTicket, KvShape, MemoryBudget, Pin, ResidencyConfig, + ResidencyManager, +}; + +pub const SLOT: u64 = 4096; +pub const MIB: u64 = 1 << 20; + +pub fn kv_none() -> KvShape { + KvShape { + layers: 0, + kv_heads: 0, + head_dim: 0, + bytes_per_element: 0, + max_context_tokens: 0, + max_sequences: 0, + } +} + +/// A config with exactly `slots` slots of `SLOT` bytes and the given +/// in-flight limits. Staging is sized to `max_in_flight_bytes`. +pub fn config(slots: u32, max_in_flight: u32, max_in_flight_bytes: u64) -> ResidencyConfig { + let staging = max_in_flight_bytes; + ResidencyConfig { + budget: MemoryBudget { + total_bytes: 1000 + staging + u64::from(slots) * SLOT + 100, + safety_headroom_bytes: 1000, + non_expert_weight_bytes: 0, + kv: kv_none(), + scratch_bytes: 0, + staging_bytes: staging, + }, + slot_bytes: SLOT, + max_slots: Some(slots), + max_in_flight, + max_in_flight_bytes, + } +} + +pub fn manager(slots: u32) -> ResidencyManager { + ResidencyManager::new(config(slots, slots.max(1), u64::from(slots.max(1)) * SLOT)).unwrap() +} + +pub fn id(layer: u32, expert: u32) -> ExpertIdentity { + ExpertIdentity { + checkpoint_digest: [7; 32], + layer, + expert, + part: ExpertPart::Down, + } +} + +/// Drive a fetch ticket all the way to Ready. +pub fn complete(m: &mut ResidencyManager, t: &FetchTicket, now: u64) { + m.mark_verified(t).unwrap(); + m.mark_copying(t).unwrap(); + m.publish(t, now).unwrap(); +} + +/// Acquire `key`, completing a fetch if it misses. Returns the pin. +pub fn load(m: &mut ResidencyManager, key: ExpertIdentity) -> Pin { + match m.acquire(key, SLOT, 0).unwrap() { + Acquired::Ready(p) | Acquired::Pending(p) => p, + Acquired::Fetch(p, t) => { + complete(m, &t, 0); + p + } + } +} + +/// Load and immediately release. +pub fn touch(m: &mut ResidencyManager, key: ExpertIdentity) { + let p = load(m, key); + m.release(p).unwrap(); +} + +/// xorshift64*: deterministic, dependency-free generator for property tests. +pub struct Rng(pub u64); + +impl Rng { + pub fn next(&mut self) -> u64 { + let mut x = self.0; + x ^= x >> 12; + x ^= x << 25; + x ^= x >> 27; + self.0 = x; + x.wrapping_mul(0x2545_F491_4F6C_DD1D) + } + pub fn below(&mut self, n: u64) -> u64 { + self.next() % n + } +} diff --git a/crates/aien-expert-residency/tests/residency_tests.rs b/crates/aien-expert-residency/tests/residency_tests.rs new file mode 100644 index 00000000..ccd8d000 --- /dev/null +++ b/crates/aien-expert-residency/tests/residency_tests.rs @@ -0,0 +1,603 @@ +mod common; + +use aien_expert_residency::{ + Acquired, ExpertIdentity, ExpertPart, ExpertState, FailureCause, Phase, Pin, PinStatus, + Refusal, ResidencyManager, Stats, +}; +use common::*; + +fn fetch(a: Acquired) -> (Pin, aien_expert_residency::FetchTicket) { + match a { + Acquired::Fetch(p, t) => (p, t), + other => panic!("expected a miss, got {other:?}"), + } +} + +#[test] +fn full_lifecycle_and_states() { + let mut m = manager(2); + let k = id(0, 5); + assert_eq!(m.state(&k), ExpertState::Absent); + let (pin, t) = fetch(m.acquire(k, SLOT, 100).unwrap()); + assert_eq!(m.state(&k), ExpertState::Fetching); + assert_eq!(m.poll(&pin), Ok(PinStatus::Waiting(Phase::Fetching))); + m.mark_verified(&t).unwrap(); + assert_eq!(m.state(&k), ExpertState::Verified); + m.mark_copying(&t).unwrap(); + assert_eq!(m.state(&k), ExpertState::Copying); + m.publish(&t, 350).unwrap(); + assert_eq!(m.state(&k), ExpertState::InUse); + assert_eq!(m.poll(&pin), Ok(PinStatus::Ready)); + m.release(pin).unwrap(); + assert_eq!(m.state(&k), ExpertState::Evictable); + let s = m.stats(); + assert_eq!((s.misses, s.published, s.hits), (1, 1, 0)); + assert_eq!((s.fetch_wait_ns_total, s.fetch_wait_ns_max), (250, 250)); + assert_eq!(s.current_resident_bytes, SLOT); + assert_eq!(s.current_pins, 0); + m.check_invariants().unwrap(); +} + +#[test] +fn published_without_pins_is_ready_not_evictable() { + let mut m = manager(2); + let k = id(1, 1); + let (pin, t) = fetch(m.acquire(k, SLOT, 0).unwrap()); + m.release(pin).unwrap(); + complete(&mut m, &t, 0); + assert_eq!(m.state(&k), ExpertState::Ready); +} + +#[test] +fn phase_steps_cannot_be_skipped_or_repeated() { + let mut m = manager(2); + let (pin, t) = fetch(m.acquire(id(0, 0), SLOT, 0).unwrap()); + let slot = t.slot(); + assert_eq!( + m.publish(&t, 0), + Err(Refusal::WrongPhase { + slot, + expected: Phase::Copying, + found: Phase::Fetching + }) + ); + assert!(matches!( + m.mark_copying(&t), + Err(Refusal::WrongPhase { .. }) + )); + m.mark_verified(&t).unwrap(); + assert!(matches!( + m.mark_verified(&t), + Err(Refusal::WrongPhase { .. }) + )); + m.mark_copying(&t).unwrap(); + m.publish(&t, 0).unwrap(); + assert!(matches!(m.publish(&t, 0), Err(Refusal::WrongPhase { .. }))); + // A published entry cannot be failed. + assert_eq!( + m.fail(&t, FailureCause::Read), + Err(Refusal::WrongPhase { + slot, + expected: Phase::Fetching, + found: Phase::Ready + }) + ); + m.release(pin).unwrap(); + m.check_invariants().unwrap(); +} + +#[test] +fn hit_and_join_counters() { + let mut m = manager(2); + let k = id(3, 9); + let (p1, t) = fetch(m.acquire(k, SLOT, 0).unwrap()); + let p2 = match m.acquire(k, SLOT, 0).unwrap() { + Acquired::Pending(p) => p, + other => panic!("{other:?}"), + }; + complete(&mut m, &t, 0); + let p3 = match m.acquire(k, SLOT, 0).unwrap() { + Acquired::Ready(p) => p, + other => panic!("{other:?}"), + }; + let s = m.stats(); + assert_eq!((s.misses, s.joined, s.hits, s.current_pins), (1, 1, 1, 3)); + for p in [p1, p2, p3] { + m.release(p).unwrap(); + } + m.check_invariants().unwrap(); +} + +#[test] +fn eviction_is_lru_and_deterministic() { + let run = || { + let mut m = manager(3); + for e in 0..3 { + touch(&mut m, id(0, e)); + } + // Use order now 0,1,2. Touch 0 so 1 is the oldest. + touch(&mut m, id(0, 0)); + let mut order = Vec::new(); + for e in 10..14 { + let victim = m.next_victim().unwrap(); + let before: Vec<_> = (0..20) + .filter(|&x| m.state(&id(0, x)) != ExpertState::Absent) + .collect(); + touch(&mut m, id(0, e)); + let after: Vec<_> = (0..20) + .filter(|&x| m.state(&id(0, x)) != ExpertState::Absent) + .collect(); + let gone: Vec<_> = before + .iter() + .filter(|x| !after.contains(x)) + .copied() + .collect(); + order.push((victim, gone)); + } + m.check_invariants().unwrap(); + (order, m.stats()) + }; + let (order, stats) = run(); + let gone: Vec = order.iter().flat_map(|(_, g)| g.clone()).collect(); + assert_eq!(gone, vec![1, 2, 0, 10]); + assert_eq!(stats.evictions, 4); + assert_eq!(run(), (order, stats), "same calls, same order"); +} + +#[test] +fn pinned_entry_is_never_evicted() { + let mut m = manager(2); + let held = load(&mut m, id(0, 0)); // oldest, but pinned + touch(&mut m, id(0, 1)); + for e in 2..50 { + touch(&mut m, id(1, e)); + assert_eq!(m.state(&id(0, 0)), ExpertState::InUse); + assert_eq!(m.poll(&held), Ok(PinStatus::Ready)); + } + m.release(held).unwrap(); + touch(&mut m, id(2, 0)); + touch(&mut m, id(2, 1)); + assert_eq!(m.state(&id(0, 0)), ExpertState::Absent); + m.check_invariants().unwrap(); +} + +#[test] +fn pinned_exhaustion_is_refused_without_side_effects() { + let mut m = manager(2); + let a = load(&mut m, id(0, 0)); + let (b, tb) = fetch(m.acquire(id(0, 1), SLOT, 0).unwrap()); // in flight + let before = m.stats(); + let r = m.acquire(id(0, 2), SLOT, 0); + assert_eq!( + r, + Err(Refusal::PinnedExhaustion { + slots: 2, + pinned: 2, + in_flight: 1 + }) + ); + let after = m.stats(); + assert_eq!(after.refusals, before.refusals + 1); + assert_eq!(after.evictions, before.evictions); + assert_eq!(m.state(&id(0, 2)), ExpertState::Absent); + // An in-flight entry with no pins is not evictable either. + m.release(b).unwrap(); + assert!(matches!( + m.acquire(id(0, 2), SLOT, 0), + Err(Refusal::PinnedExhaustion { + pinned: 1, + in_flight: 1, + .. + }) + )); + complete(&mut m, &tb, 0); + // Now id(0,1) is Ready and unpinned: it is the victim. + let (p, t) = fetch(m.acquire(id(0, 2), SLOT, 0).unwrap()); + assert_eq!(m.state(&id(0, 1)), ExpertState::Absent); + complete(&mut m, &t, 0); + m.release(p).unwrap(); + m.release(a).unwrap(); + m.check_invariants().unwrap(); +} + +#[test] +fn refused_miss_does_not_evict() { + let mut m = manager(1); + touch(&mut m, id(0, 0)); + assert_eq!( + m.acquire(id(0, 1), SLOT + 1, 0), + Err(Refusal::ObjectTooLarge { + bytes: SLOT + 1, + slot_bytes: SLOT + }) + ); + assert_eq!(m.acquire(id(0, 1), 0, 0), Err(Refusal::ZeroSizedObject)); + assert_eq!(m.state(&id(0, 0)), ExpertState::Evictable); + assert_eq!(m.stats().evictions, 0); +} + +#[test] +fn size_mismatch_is_refused() { + let mut m = manager(2); + touch(&mut m, id(0, 0)); + assert_eq!( + m.acquire(id(0, 0), SLOT - 1, 0), + Err(Refusal::SizeMismatch { + admitted: SLOT, + requested: SLOT - 1 + }) + ); + assert_eq!(m.stats().current_pins, 0); +} + +#[test] +fn backpressure_by_count_and_bytes() { + let mut m = ResidencyManager::new(config(8, 2, 3 * SLOT)).unwrap(); + let (p1, t1) = fetch(m.acquire(id(0, 0), SLOT, 0).unwrap()); + let (p2, t2) = fetch(m.acquire(id(0, 1), SLOT, 0).unwrap()); + assert_eq!( + m.acquire(id(0, 2), SLOT, 0), + Err(Refusal::InFlightLimit { limit: 2 }) + ); + // Joining an in-flight fetch is not a new fetch: allowed. + let j = m.acquire(id(0, 0), SLOT, 0).unwrap(); + complete(&mut m, &t1, 0); + assert_eq!(m.stats().current_in_flight, 1); + + let mut m2 = ResidencyManager::new(config(8, 4, 2 * SLOT)).unwrap(); + let (q1, s1) = fetch(m2.acquire(id(0, 0), SLOT, 0).unwrap()); + let (q2, s2) = fetch(m2.acquire(id(0, 1), SLOT / 2, 0).unwrap()); + assert_eq!( + m2.acquire(id(0, 2), SLOT, 0), + Err(Refusal::InFlightBytesLimit { + in_flight_bytes: SLOT + SLOT / 2, + requested: SLOT, + limit: 2 * SLOT + }) + ); + m2.fail(&s2, FailureCause::Cancelled).unwrap(); + let (q3, s3) = fetch(m2.acquire(id(0, 2), SLOT, 0).unwrap()); + for t in [&s1, &s3] { + complete(&mut m2, t, 0); + } + assert_eq!(m2.stats().peak_in_flight_bytes, 2 * SLOT); + for p in [q1, q2, q3] { + m2.release(p).unwrap(); + } + complete(&mut m, &t2, 0); + for p in [p1, p2, j.pin_owned()] { + m.release(p).unwrap(); + } + m.check_invariants().unwrap(); + m2.check_invariants().unwrap(); +} + +trait PinOwned { + fn pin_owned(self) -> Pin; +} +impl PinOwned for Acquired { + fn pin_owned(self) -> Pin { + match self { + Acquired::Ready(p) | Acquired::Pending(p) | Acquired::Fetch(p, _) => p, + } + } +} + +#[test] +fn simultaneous_readers_hold_until_last_release() { + let mut m = manager(1); + let k = id(4, 4); + let readers: Vec = (0..5).map(|_| load(&mut m, k)).collect(); + assert_eq!(m.stats().current_pins, 5); + let mut readers = readers.into_iter(); + for p in readers.by_ref().take(4) { + m.release(p).unwrap(); + assert!(matches!( + m.acquire(id(5, 5), SLOT, 0), + Err(Refusal::PinnedExhaustion { .. }) + )); + } + m.release(readers.next().unwrap()).unwrap(); + touch(&mut m, id(5, 5)); + assert_eq!(m.state(&k), ExpertState::Absent); + m.check_invariants().unwrap(); +} + +#[test] +fn layer_crossing_and_part_identities_are_distinct() { + let mut m = manager(8); + let a = id(0, 7); + let b = id(1, 7); + let mut c = id(0, 7); + c.part = ExpertPart::GateUp; + let mut d = id(0, 7); + d.checkpoint_digest = [8; 32]; + for k in [a, b, c, d] { + touch(&mut m, k); + } + assert_eq!(m.stats().misses, 4); + let slots: std::collections::BTreeSet<_> = [a, b, c, d] + .iter() + .map(|k| m.slot_of(k).unwrap().0) + .collect(); + assert_eq!(slots.len(), 4); + touch(&mut m, a); + assert_eq!(m.stats().hits, 1); +} + +#[test] +fn aba_slot_reuse_refuses_stale_pin_and_ticket() { + let mut m = manager(1); + let (old_pin, old_t) = fetch(m.acquire(id(0, 0), SLOT, 0).unwrap()); + let (slot, g1) = (old_t.slot(), old_t.generation()); + complete(&mut m, &old_t, 0); + m.release(old_pin).unwrap(); + // Reuse the same slot for another key. + let (new_pin, new_t) = fetch(m.acquire(id(9, 9), SLOT, 0).unwrap()); + assert_eq!(new_t.slot(), slot); + assert!(new_t.generation() > g1); + assert_eq!( + m.mark_verified(&old_t), + Err(Refusal::StaleTicket { + slot, + generation: g1 + }) + ); + assert_eq!( + m.fail(&old_t, FailureCause::Read), + Err(Refusal::StaleTicket { + slot, + generation: g1 + }) + ); + // Same slot, re-admitted under the original key: still a new generation. + complete(&mut m, &new_t, 0); + m.release(new_pin).unwrap(); + let (p3, t3) = fetch(m.acquire(id(0, 0), SLOT, 0).unwrap()); + assert_eq!(t3.slot(), slot); + assert!(t3.generation() > new_t.generation()); + assert!(matches!( + m.publish(&new_t, 0), + Err(Refusal::StaleTicket { .. }) + )); + m.fail(&t3, FailureCause::Cancelled).unwrap(); + assert!(matches!(m.poll(&p3), Err(Refusal::FetchFailed { .. }))); + m.release(p3).unwrap(); + m.check_invariants().unwrap(); +} + +#[test] +fn failure_with_waiters_is_explicit_and_recoverable() { + let mut m = manager(2); + let k = id(2, 3); + let (p1, t) = fetch(m.acquire(k, SLOT, 0).unwrap()); + let p2 = m.acquire(k, SLOT, 0).unwrap().pin_owned(); + m.mark_verified(&t).unwrap(); + m.fail(&t, FailureCause::DigestMismatch).unwrap(); + let failed = Err(Refusal::FetchFailed { + slot: t.slot(), + generation: t.generation(), + cause: FailureCause::DigestMismatch, + }); + assert_eq!(m.poll(&p1), failed); + assert_eq!(m.poll(&p2), failed); + // The key is unmapped at once: a retry is a clean miss in another slot. + assert_eq!(m.state(&k), ExpertState::Absent); + let (p3, t3) = fetch(m.acquire(k, SLOT, 0).unwrap()); + assert_ne!(t3.slot(), t.slot()); + // Failed slot is held for its waiters, so a third key has no room. + assert!(matches!( + m.acquire(id(7, 7), SLOT, 0), + Err(Refusal::PinnedExhaustion { .. }) + )); + m.release(p1).unwrap(); + m.release(p2).unwrap(); + complete(&mut m, &t3, 0); + m.release(p3).unwrap(); + touch(&mut m, id(7, 7)); + let s = m.stats(); + assert_eq!((s.failures, s.published), (1, 2)); + assert_eq!(s.current_in_flight, 0); + m.check_invariants().unwrap(); +} + +#[test] +fn failure_without_pins_frees_the_slot_at_once() { + let mut m = manager(1); + let (p, t) = fetch(m.acquire(id(0, 0), SLOT, 0).unwrap()); + m.release(p).unwrap(); + m.mark_verified(&t).unwrap(); + m.mark_copying(&t).unwrap(); + m.fail(&t, FailureCause::GpuFence).unwrap(); + touch(&mut m, id(0, 1)); + assert_eq!(m.stats().evictions, 0); + m.check_invariants().unwrap(); +} + +#[test] +fn acquire_all_is_all_or_nothing() { + let mut m = manager(3); + touch(&mut m, id(0, 0)); + let held = load(&mut m, id(0, 1)); + // Request needs 3 distinct new keys plus a repeat; only 2 slots usable. + let req = [ + (id(0, 1), SLOT), + (id(1, 0), SLOT), + (id(1, 0), SLOT), + (id(1, 1), SLOT), + (id(1, 2), SLOT), + ]; + let before_pins = m.stats().current_pins; + let r = m.acquire_all(&req, 0); + assert!(matches!(r, Err(Refusal::PinnedExhaustion { .. })), "{r:?}"); + let s = m.stats(); + assert_eq!(s.current_pins, before_pins); + assert_eq!(s.current_in_flight, 0); + assert_eq!(s.rolled_back, 2); + assert_eq!(m.state(&id(1, 0)), ExpertState::Absent); + assert_eq!(m.state(&id(1, 1)), ExpertState::Absent); + assert_eq!(m.state(&id(0, 1)), ExpertState::InUse); + m.check_invariants().unwrap(); + + // A request that fits: all pinned, duplicates share one fetch. + let ok = m + .acquire_all(&[(id(0, 1), SLOT), (id(2, 0), SLOT), (id(2, 0), SLOT)], 0) + .unwrap(); + assert!(matches!(ok[0], Acquired::Ready(_))); + assert!(matches!(ok[1], Acquired::Fetch(..))); + assert!(matches!(ok[2], Acquired::Pending(_))); + let mut pins = Vec::new(); + for a in ok { + match a { + Acquired::Fetch(p, t) => { + complete(&mut m, &t, 0); + pins.push(p); + } + other => pins.push(other.pin_owned()), + } + } + for p in pins { + m.release(p).unwrap(); + } + m.release(held).unwrap(); + m.check_invariants().unwrap(); +} + +/// Random operation sequences against small caches. After every operation: +/// internal invariants hold, every live pin still resolves to its own slot +/// generation (so a pinned entry was never evicted or reused), and refusals +/// leave pins untouched. The whole trace is reproduced exactly by a second +/// run with the same seed. +fn random_run(seed: u64, slots: u32, steps: usize) -> (Vec, Stats) { + let mut m = ResidencyManager::::new(config(slots, 3, 3 * SLOT)).unwrap(); + let mut rng = Rng(seed); + let mut pins: Vec<(ExpertIdentity, Pin)> = Vec::new(); + let mut tickets: Vec = Vec::new(); + let mut trace = Vec::with_capacity(steps); + for step in 0..steps { + let op = rng.below(10); + let line = match op { + 0..=3 => { + let k = id(rng.below(3) as u32, rng.below(6) as u32); + let predicted = m.next_victim(); + let evictions = m.stats().evictions; + match m.acquire(k, SLOT, step as u64) { + Ok(Acquired::Fetch(p, t)) => { + if m.stats().evictions > evictions { + assert_eq!( + Some(t.slot()), + predicted, + "seed {seed} step {step}: not the LRU victim" + ); + } + let s = format!("miss {k:?} -> {}", t.slot()); + pins.push((k, p)); + tickets.push(t); + s + } + Ok(a) => { + let s = format!("acq {a:?}"); + pins.push((k, a.pin_owned())); + s + } + Err(r) => format!("refused {r:?}"), + } + } + 4..=6 if !tickets.is_empty() => { + let i = rng.below(tickets.len() as u64) as usize; + let t = &tickets[i]; + let r = match rng.below(4) { + 0 => m.mark_verified(t), + 1 => m.mark_copying(t), + 2 => m.publish(t, step as u64), + _ => { + if rng.below(4) == 0 { + m.fail(t, FailureCause::Read) + } else { + m.publish(t, step as u64) + } + } + }; + let s = format!("step {} {r:?}", t.slot()); + let done = !matches!( + m.ticket_phase(t), + Ok(Phase::Fetching | Phase::Verified | Phase::Copying) + ); + if done { + let _finished = tickets.swap_remove(i); + } + s + } + _ if !pins.is_empty() => { + let i = rng.below(pins.len() as u64) as usize; + let (k, p) = pins.swap_remove(i); + format!("rel {k:?} {:?}", m.release(p)) + } + _ => "noop".into(), + }; + m.check_invariants() + .unwrap_or_else(|e| panic!("seed {seed} step {step} {line}: {e}")); + for (k, p) in &pins { + match m.poll(p) { + Ok(_) => { + let (slot, g) = m.slot_of(k).expect("pinned key must stay admitted"); + assert_eq!( + (slot, g), + (p.slot(), p.generation()), + "seed {seed} step {step}" + ); + } + Err(Refusal::FetchFailed { .. }) => {} + Err(e) => panic!("seed {seed} step {step}: live pin refused {e:?}"), + } + } + trace.push(line); + } + let stats = m.stats(); + // Drain: every remaining ticket is still in flight; fail it, then + // release every pin. The cache must be fully evictable again. + for t in tickets.drain(..) { + m.fail(&t, FailureCause::Cancelled).unwrap(); + } + for (_, p) in pins.drain(..) { + m.release(p).unwrap(); + } + m.check_invariants().unwrap(); + assert_eq!(m.stats().current_pins, 0); + assert_eq!(m.stats().current_in_flight, 0); + (trace, stats) +} + +#[test] +fn property_random_sequences_hold_invariants() { + let mut total = Stats::default(); + for seed in 1..=40u64 { + for slots in [1u32, 2, 3, 5] { + let (_, s) = random_run(seed * 0x1000_0001 + u64::from(slots), slots, 400); + total.hits += s.hits; + total.joined += s.joined; + total.evictions += s.evictions; + total.failures += s.failures; + total.refusals += s.refusals; + total.published += s.published; + } + } + // The generator must actually reach every interesting path. + eprintln!("property totals: {total:?}"); + assert!( + total.hits > 0 + && total.joined > 0 + && total.evictions > 0 + && total.failures > 0 + && total.refusals > 0 + && total.published > 0, + "{total:?}" + ); +} + +#[test] +fn property_traces_are_deterministic() { + for seed in [3u64, 99, 12345] { + assert_eq!(random_run(seed, 3, 600), random_run(seed, 3, 600)); + } +}