diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile_fill.rs b/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile_fill.rs index b66d15ff..57d67f48 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile_fill.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile_fill.rs @@ -143,3 +143,6 @@ mod impl_moeweightcache_2; mod impl_moeweightcache_3; #[path = "cache_profile_fill/impl_moeweightcache_4.rs"] mod impl_moeweightcache_4; +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +#[path = "cache_profile_fill/profile_build_fns.rs"] +mod profile_build_fns; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile_fill/impl_moeweightcache_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile_fill/impl_moeweightcache_2.rs index e79600a4..2aacd2d0 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile_fill/impl_moeweightcache_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile_fill/impl_moeweightcache_2.rs @@ -1,6 +1,8 @@ //! Moved out of the parent module by STRA-338: impl MoeWeightCache. #[allow(unused_imports)] +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +use super::profile_build_fns::ProfileKind; use super::*; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] @@ -14,165 +16,7 @@ impl<'ctx> MoeWeightCache<'ctx> { ) -> Result { let profile = RankedProfile::parse(bytes, PROFILE_SHA)?; let mut cache = Self::new_native_integer_iq3_mmq_retained_mtp_kv_shared_tail_lru(binding, context)?; - let operation = (|| { - cache.validate(binding, context)?; - cache.admit_mtp_input_workspace(binding)?; - let baseline = cache.counters; - let mut layer_keys = Vec::new(); - layer_keys.try_reserve_exact(48).map_err(|_| Error::InputAllocation)?; - let mut shared_keys = Vec::new(); - shared_keys.try_reserve_exact(48).map_err(|_| Error::InputAllocation)?; - let mut charges = [[0usize; 3]; 48]; - for (layer, charge) in charges.iter_mut().enumerate() { - let keys = [ - binding.moe_preload_descriptor(layer as u32, 0, MoeMatrixRole::Gate).map_err(binding_error)?, - binding.moe_preload_descriptor(layer as u32, 0, MoeMatrixRole::Up).map_err(binding_error)?, - binding.moe_preload_descriptor(layer as u32, 0, MoeMatrixRole::Down).map_err(binding_error)?, - ]; - for (n, key) in keys.iter().enumerate() { - charge[n] = cache.weight_layout(*key)?.map_or(key.bytes, |(_, bytes)| bytes); - } - layer_keys.push(keys); - shared_keys.push(binding.moe_shared_preload_descriptors(layer as u32).map_err(binding_error)?); - } - let mut shared = cache_profile::SharedPermanentPool::new(shared_keys)?; - shared.baseline = - [baseline.hits, baseline.misses, baseline.read_bytes, baseline.upload_bytes, baseline.eviction_bytes]; - let remaining_main = cache_profile::remaining_shared_main(MAIN_LIMIT, shared.bytes)?; - let mut totals = [0usize; 48]; - for (total, roles) in totals.iter_mut().zip(charges) { - *total = roles.into_iter().try_fold(0usize, |n, v| n.checked_add(v)).ok_or(Error::Overflow)?; - } - let minimum = *totals.iter().min().ok_or(Error::InvalidDimension)?; - let largest = *totals.iter().max().ok_or(Error::InvalidDimension)?; - if minimum == 0 { - return Err(Error::InvalidDimension); - } - let window_spill = profile_window_spill_with_floor(1usize << 30)?; - let spill = window_spill.checked_add(largest).ok_or(Error::Overflow)?; - // Metadata for even the largest possible selected prefix is charged BEFORE H2D. - let maximum_count = remaining_main - .checked_sub(spill) - .ok_or(Error::InputAllocation)? - .checked_div(minimum) - .ok_or(Error::InvalidDimension)? - .min(profile.ordered_pairs().len()) - .checked_mul(3) - .and_then(|n| n.checked_add(shared.descriptor_count())) - .ok_or(Error::Overflow)?; - cache.main.try_reserve(maximum_count.max(1 << 15)).map_err(|_| Error::InputAllocation)?; - let main_slot_limit = cache.main.capacity(); - let mut selected = Vec::new(); - selected.try_reserve_exact(48 * 512).map_err(|_| Error::InputAllocation)?; - selected.resize(48 * 512, false); - let buckets = - main_slot_limit.checked_mul(4).and_then(|n| n.checked_add(2)).map(|n| n / 3).ok_or(Error::Overflow)?; - let map_bytes = buckets - .checked_mul(std::mem::size_of::<(MoeWeightDescriptor, Entry<'ctx>)>() + 1) - .and_then(|n| n.checked_add(16 + std::mem::size_of::>>())) - .ok_or(Error::Overflow)?; - let metadata_bytes = profile - .metadata_bytes() - .checked_add(shared.metadata_bytes()?) - .and_then(|n| n.checked_add(selected.capacity() * std::mem::size_of::())) - .and_then(|n| n.checked_add(std::mem::size_of::())) - .and_then(|n| n.checked_add(std::mem::size_of::())) - .and_then(|n| n.checked_add(bytes.len())) - .and_then(|n| n.checked_add(layer_keys.capacity() * std::mem::size_of::<[MoeWeightDescriptor; 3]>())) - .and_then(|n| n.checked_add(cache.lru.as_ref()?.metadata_bytes().ok()?)) - .and_then(|n| n.checked_add(map_bytes)) - .ok_or(Error::Overflow)?; - if metadata_bytes > HOST_CAP || maximum_count > main_slot_limit { - return Err(Error::InputAllocation); - } - // Closed source/geometry was checked for every descriptor above. Only - // full finite actual owned bytes from the same binding are uploaded. - for layer in 0..48 { - let keys = shared.quartet(layer)?; - cache.preload_shared_quartet(binding, keys, spill, &mut shared)?; - } - if cache.main_bytes != shared.bytes - || cache.main.len() != shared.descriptor_count() - || cache.lru.as_ref().ok_or(Error::IdentityMismatch)?.len() != 0 - { - return Err(Error::IdentityMismatch); - } - // Actual owners now appear in both allocated_bytes and physical_free. - // Subtract their bytes ONLY from the remaining main pool. - let (free, _) = context.memory_info().map_err(driver_error)?; - let plan = PrefixPlan::new_shared_with_storage( - &profile, - &charges, - ProfileLimits { - main_cap: remaining_main, - allocated: context.allocated_bytes(), - device_budget: context.budget_bytes(), - physical_free: free, - working_reserve: WORKING_RESERVE, - window_spill, - }, - selected, - )?; - let count = plan.prefix.checked_mul(3).ok_or(Error::Overflow)?; - if count.checked_add(shared.descriptor_count()).is_none_or(|n| n > main_slot_limit) { - return Err(Error::InputAllocation); - } - let expected_bytes = plan.charged_bytes.checked_add(shared.bytes).ok_or(Error::Overflow)?; - let shared_bytes = shared.bytes as u64; - cache.pinned = Some(PinnedPool { - plan, - loaded_matrices: 0, - shared: Some(shared), - #[cfg(test)] - metadata_bytes, - main_slot_limit, - #[cfg(test)] - fixed_resident_upload_bytes: baseline.upload_bytes, - #[cfg(test)] - fixed_resident_read_bytes: baseline.read_bytes, - pinned_hits: 0, - spill_hits: 0, - spill_misses: 0, - preload_read_bytes: shared_bytes, - preload_upload_bytes: shared_bytes, - }); - let prefix = cache.pinned.as_ref().ok_or(Error::IdentityMismatch)?.plan.prefix; - for &(layer, expert) in &profile.ordered_pairs()[..prefix] { - let keys = [ - binding - .moe_preload_descriptor(u32::from(layer), u32::from(expert), MoeMatrixRole::Gate) - .map_err(binding_error)?, - binding - .moe_preload_descriptor(u32::from(layer), u32::from(expert), MoeMatrixRole::Up) - .map_err(binding_error)?, - binding - .moe_preload_descriptor(u32::from(layer), u32::from(expert), MoeMatrixRole::Down) - .map_err(binding_error)?, - ]; - let mut topology_keys = layer_keys[usize::from(layer)]; - for key in &mut topology_keys { - key.expert = Some(u32::from(expert)); - } - if keys != topology_keys { - return Err(Error::IdentityMismatch); - } - cache.preload_pinned_triplet(binding, keys)?; - } - if cache.main_bytes != expected_bytes - || cache.spill_len()? != 0 - || cache.pinned.as_ref().is_none_or(|pool| pool.loaded_matrices != count) - { - return Err(Error::IdentityMismatch); - } - cache - .pinned - .as_mut() - .and_then(|pool| pool.shared.as_mut()) - .ok_or(Error::IdentityMismatch)? - .finish_preload(); - cache.validate(binding, context) - })(); - if let Err(primary) = operation { + if let Err(primary) = cache.build_profile(binding, context, &profile, bytes.len(), ProfileKind::Fixed) { let _ = cache.close(); return Err(primary); } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile_fill/impl_moeweightcache_3.rs b/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile_fill/impl_moeweightcache_3.rs index fa5a4feb..495cbb2e 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile_fill/impl_moeweightcache_3.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile_fill/impl_moeweightcache_3.rs @@ -1,6 +1,8 @@ //! Moved out of the parent module by STRA-338: impl MoeWeightCache, impl MoeWeightCache. #[allow(unused_imports)] +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +use super::profile_build_fns::ProfileKind; use super::*; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] @@ -14,183 +16,7 @@ impl<'ctx> MoeWeightCache<'ctx> { let profile = RankedProfile::parse(bytes, PROFILE_SHA)?; let mut cache = Self::new_native_integer_iq3_mmq_retained_mtp_kv_shared_tail_lru_with_prompt(binding, context, true)?; - let operation = (|| { - cache.validate(binding, context)?; - cache.admit_mtp_input_workspace(binding)?; - let baseline = cache.counters; - let mut layer_keys = Vec::new(); - layer_keys.try_reserve_exact(48).map_err(|_| Error::InputAllocation)?; - let mut shared_keys = Vec::new(); - shared_keys.try_reserve_exact(48).map_err(|_| Error::InputAllocation)?; - let mut charges = [[0usize; 3]; 48]; - for (layer, charge) in charges.iter_mut().enumerate() { - let keys = [ - binding.moe_preload_descriptor(layer as u32, 0, MoeMatrixRole::Gate).map_err(binding_error)?, - binding.moe_preload_descriptor(layer as u32, 0, MoeMatrixRole::Up).map_err(binding_error)?, - binding.moe_preload_descriptor(layer as u32, 0, MoeMatrixRole::Down).map_err(binding_error)?, - ]; - for (n, key) in keys.iter().enumerate() { - charge[n] = cache.weight_layout(*key)?.map_or(key.bytes, |(_, bytes)| bytes); - } - layer_keys.push(keys); - shared_keys.push(binding.moe_shared_preload_descriptors(layer as u32).map_err(binding_error)?); - } - let mut shared = cache_profile::SharedPermanentPool::new(shared_keys)?; - shared.baseline = - [baseline.hits, baseline.misses, baseline.read_bytes, baseline.upload_bytes, baseline.eviction_bytes]; - let remaining_main = cache_profile::remaining_shared_main(MAIN_LIMIT, shared.bytes)?; - let mut totals = [0usize; 48]; - for (total, roles) in totals.iter_mut().zip(charges) { - *total = roles.into_iter().try_fold(0usize, |n, v| n.checked_add(v)).ok_or(Error::Overflow)?; - } - let minimum = *totals.iter().min().ok_or(Error::InvalidDimension)?; - let largest = *totals.iter().max().ok_or(Error::InvalidDimension)?; - if minimum == 0 { - return Err(Error::InvalidDimension); - } - let window_spill = profile_window_spill_with_floor(1usize << 30)?; - let spill = window_spill.checked_add(largest).ok_or(Error::Overflow)?; - // Metadata for even the largest possible selected prefix is charged BEFORE H2D. - let maximum_count = cache_profile::learned_main_slot_bound(&charges, remaining_main)? - .checked_add(shared.descriptor_count()) - .ok_or(Error::Overflow)?; - cache.main.try_reserve(maximum_count.max(1 << 15)).map_err(|_| Error::InputAllocation)?; - let main_slot_limit = cache.main.capacity(); - let mut selected = Vec::new(); - selected.try_reserve_exact(48 * 512).map_err(|_| Error::InputAllocation)?; - selected.resize(48 * 512, false); - let buckets = - main_slot_limit.checked_mul(4).and_then(|n| n.checked_add(2)).map(|n| n / 3).ok_or(Error::Overflow)?; - let map_bytes = buckets - .checked_mul(std::mem::size_of::<(MoeWeightDescriptor, Entry<'ctx>)>() + 1) - .and_then(|n| n.checked_add(16 + std::mem::size_of::>>())) - .ok_or(Error::Overflow)?; - let metadata_bytes = profile - .metadata_bytes() - .checked_add(shared.metadata_bytes()?) - .and_then(|n| n.checked_add(selected.capacity() * std::mem::size_of::())) - .and_then(|n| n.checked_add(std::mem::size_of::())) - .and_then(|n| n.checked_add(std::mem::size_of::())) - .and_then(|n| n.checked_add(bytes.len())) - .and_then(|n| n.checked_add(layer_keys.capacity() * std::mem::size_of::<[MoeWeightDescriptor; 3]>())) - .and_then(|n| n.checked_add(cache.lru.as_ref()?.metadata_bytes().ok()?)) - .and_then(|n| n.checked_add(map_bytes)) - .and_then(|n| n.checked_add(std::mem::size_of::())) - .and_then(|n| n.checked_add(std::mem::size_of::<[usize; 144]>())) - .ok_or(Error::Overflow)?; - if metadata_bytes > HOST_CAP || maximum_count > main_slot_limit { - return Err(Error::InputAllocation); - } - cache.learned_metadata_bytes = metadata_bytes; - // Closed source/geometry was checked for every descriptor above. Only - // full finite actual owned bytes from the same binding are uploaded. - for layer in 0..48 { - let keys = shared.quartet(layer)?; - cache.preload_shared_quartet(binding, keys, spill, &mut shared)?; - } - if cache.main_bytes != shared.bytes - || cache.main.len() != shared.descriptor_count() - || cache.lru.as_ref().ok_or(Error::IdentityMismatch)?.len() != 0 - { - return Err(Error::IdentityMismatch); - } - // Actual owners now appear in both allocated_bytes and physical_free. - // Subtract their bytes ONLY from the remaining main pool. - let (free, _) = context.memory_info().map_err(driver_error)?; - let plan = PrefixPlan::new_shared_with_storage( - &profile, - &charges, - ProfileLimits { - main_cap: remaining_main, - allocated: context.allocated_bytes(), - device_budget: context.budget_bytes(), - physical_free: free, - working_reserve: WORKING_RESERVE, - window_spill, - }, - selected, - )?; - let count = plan.prefix.checked_mul(3).ok_or(Error::Overflow)?; - if count.checked_add(shared.descriptor_count()).is_none_or(|n| n > main_slot_limit) { - return Err(Error::InputAllocation); - } - let expected_bytes = plan.charged_bytes.checked_add(shared.bytes).ok_or(Error::Overflow)?; - let shared_bytes = shared.bytes as u64; - cache.pinned = Some(PinnedPool { - plan, - loaded_matrices: 0, - shared: Some(shared), - #[cfg(test)] - metadata_bytes, - main_slot_limit, - #[cfg(test)] - fixed_resident_upload_bytes: baseline.upload_bytes, - #[cfg(test)] - fixed_resident_read_bytes: baseline.read_bytes, - pinned_hits: 0, - spill_hits: 0, - spill_misses: 0, - preload_read_bytes: shared_bytes, - preload_upload_bytes: shared_bytes, - }); - let prefix = cache.pinned.as_ref().ok_or(Error::IdentityMismatch)?.plan.prefix; - for &(layer, expert) in &profile.ordered_pairs()[..prefix] { - let keys = [ - binding - .moe_preload_descriptor(u32::from(layer), u32::from(expert), MoeMatrixRole::Gate) - .map_err(binding_error)?, - binding - .moe_preload_descriptor(u32::from(layer), u32::from(expert), MoeMatrixRole::Up) - .map_err(binding_error)?, - binding - .moe_preload_descriptor(u32::from(layer), u32::from(expert), MoeMatrixRole::Down) - .map_err(binding_error)?, - ]; - let mut topology_keys = layer_keys[usize::from(layer)]; - for key in &mut topology_keys { - key.expert = Some(u32::from(expert)); - } - if keys != topology_keys { - return Err(Error::IdentityMismatch); - } - cache.preload_pinned_triplet(binding, keys)?; - } - if cache.main_bytes != expected_bytes - || cache.spill_len()? != 0 - || cache.pinned.as_ref().is_none_or(|pool| pool.loaded_matrices != count) - { - return Err(Error::IdentityMismatch); - } - cache - .pinned - .as_mut() - .and_then(|pool| pool.shared.as_mut()) - .ok_or(Error::IdentityMismatch)? - .finish_preload(); - // The same real owners are already complete. Seed the existing empty - // metadata only; no source read, allocation or H2D occurs here. - let shared = cache.pinned.as_ref().and_then(|pool| pool.shared.as_ref()).ok_or(Error::IdentityMismatch)?; - for (key, entry) in &cache.main { - let expected = cache.weight_layout(*key)?.map_or(key.bytes, |(_, charge)| charge); - if entry.charged_bytes != expected - || entry.age == 0 - || entry.age > cache.age - || (key.expert.is_none() && !shared.contains(*key)) - { - return Err(Error::IdentityMismatch); - } - } - cache.lru.as_mut().ok_or(Error::IdentityMismatch)?.seed_existing( - cache.age, - cache.main.iter().filter(|(key, _)| !shared.contains(**key)).map(|(key, entry)| (*key, entry.age)), - )?; - cache.learned_main = true; - if cache.lru.as_ref().ok_or(Error::IdentityMismatch)?.len() != cache.spill_len()? { - return Err(Error::IdentityMismatch); - } - cache.validate(binding, context) - })(); - if let Err(primary) = operation { + if let Err(primary) = cache.build_profile(binding, context, &profile, bytes.len(), ProfileKind::Learned) { let _ = cache.close(); return Err(primary); } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile_fill/profile_build_fns.rs b/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile_fill/profile_build_fns.rs new file mode 100644 index 00000000..ab6d3b21 --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile_fill/profile_build_fns.rs @@ -0,0 +1,374 @@ +//! The shared-permanent profile build behind the fixed-prefix and learned-main constructors (STRA-338 size: +//! extract-method only). + +#[allow(unused_imports)] +use super::*; + +/// Which sizing and seeding the profile build uses. +#[allow(dead_code)] +#[derive(Clone, Copy, PartialEq, Eq)] +pub(super) enum ProfileKind { + /// Ranked prefix only: the pinned pool is the whole selection. + Fixed, + /// Genuine preload bytes first, then the routed main residency is learned. + Learned, +} + +type LayerKeys = Vec<[MoeWeightDescriptor; 3]>; +type SharedKeys = Vec<[MoeWeightDescriptor; 4]>; + +/// The first-expert descriptors, shared descriptors and per-layer charges of every layer. +struct ProfileLayers { + layer_keys: LayerKeys, + shared_keys: SharedKeys, + charges: [[usize; 3]; 48], +} + +/// The spill window, main slot limit and host metadata the profile build is admitted against. +struct ProfileBudget { + remaining_main: usize, + window_spill: usize, + spill: usize, + main_slot_limit: usize, + selected: Vec, + metadata_bytes: usize, +} + +impl<'ctx> MoeWeightCache<'ctx> { + pub(super) fn build_profile( + &mut self, + binding: &ModelBinding, + context: &'ctx Context<'ctx>, + profile: &RankedProfile, + bytes_len: usize, + kind: ProfileKind, + ) -> Result<()> { + let (layers, mut shared, baseline) = self.profile_open(binding, context)?; + let budget = self.profile_budget(kind, profile, bytes_len, &layers, &shared)?; + if kind == ProfileKind::Learned { + self.learned_metadata_bytes = budget.metadata_bytes; + } + // Closed source/geometry was checked for every descriptor above. Only + // full finite actual owned bytes from the same binding are uploaded. + self.profile_preload_shared(binding, &mut shared, budget.spill)?; + let expected_bytes = self.profile_pin(context, profile, &layers, shared, budget, baseline)?; + self.profile_preload_pinned(binding, profile, &layers.layer_keys, expected_bytes)?; + if kind == ProfileKind::Learned { + self.seed_learned_main()?; + } + self.validate(binding, context) + } + + /// Validate, admit the MTP input workspace and size the layers and the shared permanent pool. + fn profile_open( + &mut self, + binding: &ModelBinding, + context: &'ctx Context<'ctx>, + ) -> Result<(ProfileLayers, cache_profile::SharedPermanentPool, WeightCacheCounters)> { + self.validate(binding, context)?; + self.admit_mtp_input_workspace(binding)?; + let baseline = self.counters; + let mut layers = self.profile_layers(binding)?; + let mut shared = cache_profile::SharedPermanentPool::new(std::mem::take(&mut layers.shared_keys))?; + shared.baseline = + [baseline.hits, baseline.misses, baseline.read_bytes, baseline.upload_bytes, baseline.eviction_bytes]; + Ok((layers, shared, baseline)) + } + + fn profile_layers(&self, binding: &ModelBinding) -> Result { + let mut layer_keys = Vec::new(); + layer_keys.try_reserve_exact(48).map_err(|_| Error::InputAllocation)?; + let mut shared_keys = Vec::new(); + shared_keys.try_reserve_exact(48).map_err(|_| Error::InputAllocation)?; + let mut charges = [[0usize; 3]; 48]; + for (layer, charge) in charges.iter_mut().enumerate() { + let keys = [ + binding.moe_preload_descriptor(layer as u32, 0, MoeMatrixRole::Gate).map_err(binding_error)?, + binding.moe_preload_descriptor(layer as u32, 0, MoeMatrixRole::Up).map_err(binding_error)?, + binding.moe_preload_descriptor(layer as u32, 0, MoeMatrixRole::Down).map_err(binding_error)?, + ]; + for (n, key) in keys.iter().enumerate() { + charge[n] = self.weight_layout(*key)?.map_or(key.bytes, |(_, bytes)| bytes); + } + layer_keys.push(keys); + shared_keys.push(binding.moe_shared_preload_descriptors(layer as u32).map_err(binding_error)?); + } + Ok(ProfileLayers { layer_keys, shared_keys, charges }) + } + + fn profile_budget( + &mut self, + kind: ProfileKind, + profile: &RankedProfile, + bytes_len: usize, + layers: &ProfileLayers, + shared: &cache_profile::SharedPermanentPool, + ) -> Result { + let remaining_main = cache_profile::remaining_shared_main(MAIN_LIMIT, shared.bytes)?; + let (minimum, largest) = charge_extremes(&layers.charges)?; + let window_spill = profile_window_spill_with_floor(1usize << 30)?; + let spill = window_spill.checked_add(largest).ok_or(Error::Overflow)?; + // Metadata for even the largest possible selected prefix is charged BEFORE H2D. + let maximum_count = profile_maximum(kind, profile, &layers.charges, remaining_main, spill, minimum, shared)?; + self.main.try_reserve(maximum_count.max(1 << 15)).map_err(|_| Error::InputAllocation)?; + let main_slot_limit = self.main.capacity(); + let selected = selected_flags()?; + let metadata_bytes = self.profile_metadata(kind, profile, bytes_len, layers, shared, selected.capacity())?; + check_budget(metadata_bytes, maximum_count, main_slot_limit)?; + Ok(ProfileBudget { remaining_main, window_spill, spill, main_slot_limit, selected, metadata_bytes }) + } + + fn profile_metadata( + &self, + kind: ProfileKind, + profile: &RankedProfile, + bytes_len: usize, + layers: &ProfileLayers, + shared: &cache_profile::SharedPermanentPool, + selected_capacity: usize, + ) -> Result { + let map_bytes = self.main_map_bytes()?; + let learned_extra = if kind == ProfileKind::Learned { + std::mem::size_of::() + std::mem::size_of::<[usize; 144]>() + } else { + 0 + }; + profile + .metadata_bytes() + .checked_add(shared.metadata_bytes()?) + .and_then(|n| n.checked_add(selected_capacity * std::mem::size_of::())) + .and_then(|n| n.checked_add(std::mem::size_of::())) + .and_then(|n| n.checked_add(std::mem::size_of::())) + .and_then(|n| n.checked_add(bytes_len)) + .and_then(|n| n.checked_add(layers.layer_keys.capacity() * std::mem::size_of::<[MoeWeightDescriptor; 3]>())) + .and_then(|n| n.checked_add(self.lru.as_ref()?.metadata_bytes().ok()?)) + .and_then(|n| n.checked_add(map_bytes)) + .and_then(|n| n.checked_add(learned_extra)) + .ok_or(Error::Overflow) + } + + fn main_map_bytes(&self) -> Result { + let buckets = self.main.capacity().checked_mul(4).and_then(|n| n.checked_add(2)).map(|n| n / 3); + buckets + .ok_or(Error::Overflow)? + .checked_mul(std::mem::size_of::<(MoeWeightDescriptor, Entry<'ctx>)>() + 1) + .and_then(|n| n.checked_add(16 + std::mem::size_of::>>())) + .ok_or(Error::Overflow) + } + + fn profile_preload_shared( + &mut self, + binding: &ModelBinding, + shared: &mut cache_profile::SharedPermanentPool, + spill: usize, + ) -> Result<()> { + for layer in 0..48 { + let keys = shared.quartet(layer)?; + self.preload_shared_quartet(binding, keys, spill, shared)?; + } + if self.main_bytes != shared.bytes + || self.main.len() != shared.descriptor_count() + || self.lru.as_ref().ok_or(Error::IdentityMismatch)?.len() != 0 + { + return Err(Error::IdentityMismatch); + } + Ok(()) + } + + /// Actual owners now appear in both allocated_bytes and physical_free. Subtract their bytes ONLY from the + /// remaining main pool. Returns the byte total the pinned preload must reach. + fn profile_pin( + &mut self, + context: &'ctx Context<'ctx>, + profile: &RankedProfile, + layers: &ProfileLayers, + shared: cache_profile::SharedPermanentPool, + budget: ProfileBudget, + baseline: WeightCacheCounters, + ) -> Result { + let limits = profile_limits(context, budget.remaining_main, budget.window_spill)?; + let plan = PrefixPlan::new_shared_with_storage(profile, &layers.charges, limits, budget.selected)?; + let count = plan.prefix.checked_mul(3).ok_or(Error::Overflow)?; + if count.checked_add(shared.descriptor_count()).is_none_or(|n| n > budget.main_slot_limit) { + return Err(Error::InputAllocation); + } + let expected_bytes = plan.charged_bytes.checked_add(shared.bytes).ok_or(Error::Overflow)?; + self.pinned = Some(pinned_pool(plan, shared, budget.main_slot_limit, budget.metadata_bytes, baseline)); + Ok(expected_bytes) + } + + fn profile_preload_pinned( + &mut self, + binding: &ModelBinding, + profile: &RankedProfile, + layer_keys: &LayerKeys, + expected_bytes: usize, + ) -> Result<()> { + let prefix = self.pinned.as_ref().ok_or(Error::IdentityMismatch)?.plan.prefix; + let count = prefix.checked_mul(3).ok_or(Error::Overflow)?; + for &(layer, expert) in &profile.ordered_pairs()[..prefix] { + let keys = pinned_keys(binding, layer_keys, layer, expert)?; + self.preload_pinned_triplet(binding, keys)?; + } + self.finish_pinned(expected_bytes, count) + } + + fn finish_pinned(&mut self, expected_bytes: usize, count: usize) -> Result<()> { + if self.main_bytes != expected_bytes + || self.spill_len()? != 0 + || self.pinned.as_ref().is_none_or(|pool| pool.loaded_matrices != count) + { + return Err(Error::IdentityMismatch); + } + let shared = self.pinned.as_mut().and_then(|pool| pool.shared.as_mut()); + shared.ok_or(Error::IdentityMismatch)?.finish_preload(); + Ok(()) + } + + /// Every cached entry must carry its exact charge, a live age and, if unrouted, a shared permanent identity. + fn check_main_entries(&self, shared: &cache_profile::SharedPermanentPool) -> Result<()> { + for (key, entry) in &self.main { + let expected = self.weight_layout(*key)?.map_or(key.bytes, |(_, charge)| charge); + if entry.charged_bytes != expected + || entry.age == 0 + || entry.age > self.age + || (key.expert.is_none() && !shared.contains(*key)) + { + return Err(Error::IdentityMismatch); + } + } + Ok(()) + } + + /// The same real owners are already complete. Seed the existing empty metadata only; no source read, allocation + /// or H2D occurs here. + fn seed_learned_main(&mut self) -> Result<()> { + let shared = self.pinned.as_ref().and_then(|pool| pool.shared.as_ref()).ok_or(Error::IdentityMismatch)?; + self.check_main_entries(shared)?; + let resident = + self.main.iter().filter(|(key, _)| !shared.contains(**key)).map(|(key, entry)| (*key, entry.age)); + self.lru.as_mut().ok_or(Error::IdentityMismatch)?.seed_existing(self.age, resident)?; + self.learned_main = true; + if self.lru.as_ref().ok_or(Error::IdentityMismatch)?.len() != self.spill_len()? { + return Err(Error::IdentityMismatch); + } + Ok(()) + } +} + +fn check_budget(metadata_bytes: usize, maximum_count: usize, main_slot_limit: usize) -> Result<()> { + if metadata_bytes > HOST_CAP || maximum_count > main_slot_limit { + return Err(Error::InputAllocation); + } + Ok(()) +} + +fn selected_flags() -> Result> { + let mut selected = Vec::new(); + selected.try_reserve_exact(48 * 512).map_err(|_| Error::InputAllocation)?; + selected.resize(48 * 512, false); + Ok(selected) +} + +/// The smallest and largest per-layer charge; an empty layer is refused. +fn charge_extremes(charges: &[[usize; 3]; 48]) -> Result<(usize, usize)> { + let mut totals = [0usize; 48]; + for (total, roles) in totals.iter_mut().zip(charges) { + *total = roles.iter().try_fold(0usize, |n, v| n.checked_add(*v)).ok_or(Error::Overflow)?; + } + let minimum = *totals.iter().min().ok_or(Error::InvalidDimension)?; + let largest = *totals.iter().max().ok_or(Error::InvalidDimension)?; + if minimum == 0 { + return Err(Error::InvalidDimension); + } + Ok((minimum, largest)) +} + +/// Metadata slot bound for the fixed prefix or the learned main residency, plus the shared descriptors. +fn profile_maximum( + kind: ProfileKind, + profile: &RankedProfile, + charges: &[[usize; 3]; 48], + remaining_main: usize, + spill: usize, + minimum: usize, + shared: &cache_profile::SharedPermanentPool, +) -> Result { + if kind == ProfileKind::Learned { + return cache_profile::learned_main_slot_bound(charges, remaining_main)? + .checked_add(shared.descriptor_count()) + .ok_or(Error::Overflow); + } + remaining_main + .checked_sub(spill) + .ok_or(Error::InputAllocation)? + .checked_div(minimum) + .ok_or(Error::InvalidDimension)? + .min(profile.ordered_pairs().len()) + .checked_mul(3) + .and_then(|n| n.checked_add(shared.descriptor_count())) + .ok_or(Error::Overflow) +} + +/// The Gate/Up/Down descriptors of one pinned expert; they must equal the layer's topology with the expert filled in. +fn pinned_keys( + binding: &ModelBinding, + layer_keys: &LayerKeys, + layer: u16, + expert: u16, +) -> Result<[MoeWeightDescriptor; 3]> { + let (layer32, expert32) = (u32::from(layer), u32::from(expert)); + let keys = [ + binding.moe_preload_descriptor(layer32, expert32, MoeMatrixRole::Gate).map_err(binding_error)?, + binding.moe_preload_descriptor(layer32, expert32, MoeMatrixRole::Up).map_err(binding_error)?, + binding.moe_preload_descriptor(layer32, expert32, MoeMatrixRole::Down).map_err(binding_error)?, + ]; + let mut topology_keys = layer_keys[usize::from(layer)]; + for key in &mut topology_keys { + key.expert = Some(expert32); + } + if keys != topology_keys { + return Err(Error::IdentityMismatch); + } + Ok(keys) +} + +fn profile_limits(context: &Context<'_>, remaining_main: usize, window_spill: usize) -> Result { + let (free, _) = context.memory_info().map_err(driver_error)?; + Ok(ProfileLimits { + main_cap: remaining_main, + allocated: context.allocated_bytes(), + device_budget: context.budget_bytes(), + physical_free: free, + working_reserve: WORKING_RESERVE, + window_spill, + }) +} + +#[cfg_attr(not(test), allow(unused_variables))] +fn pinned_pool( + plan: PrefixPlan, + shared: cache_profile::SharedPermanentPool, + main_slot_limit: usize, + metadata_bytes: usize, + baseline: WeightCacheCounters, +) -> PinnedPool { + let shared_bytes = shared.bytes as u64; + PinnedPool { + plan, + loaded_matrices: 0, + shared: Some(shared), + #[cfg(test)] + metadata_bytes, + main_slot_limit, + #[cfg(test)] + fixed_resident_upload_bytes: baseline.upload_bytes, + #[cfg(test)] + fixed_resident_read_bytes: baseline.read_bytes, + pinned_hits: 0, + spill_hits: 0, + spill_misses: 0, + preload_read_bytes: shared_bytes, + preload_upload_bytes: shared_bytes, + } +}