diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile_fill/impl_moeweightcache_4.rs b/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile_fill/impl_moeweightcache_4.rs index a80d02be..ca812e98 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile_fill/impl_moeweightcache_4.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile_fill/impl_moeweightcache_4.rs @@ -34,174 +34,283 @@ 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, mapped)?; - let operation = (|| { - cache.validate(binding, context)?; - let required = 46_612usize.checked_add(WORKING_RESERVE).ok_or(Error::Overflow)?; - let (free, _) = context.memory_info().map_err(driver_error)?; - if free < required - || context.allocated_bytes().checked_add(required).is_none_or(|n| n > context.budget_bytes()) - { - return Err(Error::InputAllocation); - } - cache.routed_resident = Some(Rc::new(super::super::RoutedResidentOwner::new(context)?)); - cache.admit_mtp_input_workspace(binding)?; - 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 largest = 0usize; - for layer in 0..48 { - let keys = [ - binding.moe_preload_descriptor(layer, 0, MoeMatrixRole::Gate).map_err(binding_error)?, - binding.moe_preload_descriptor(layer, 0, MoeMatrixRole::Up).map_err(binding_error)?, - binding.moe_preload_descriptor(layer, 0, MoeMatrixRole::Down).map_err(binding_error)?, - ]; - largest = - largest.max(keys.iter().try_fold(0usize, |n, k| n.checked_add(k.bytes).ok_or(Error::Overflow))?); - layer_keys.push(keys); - shared_keys.push(binding.moe_shared_preload_descriptors(layer).map_err(binding_error)?); - } - let template: [[MoeWeightDescriptor; 3]; 48] = - layer_keys.try_into().map_err(|_| Error::InvalidDimension)?; - // These are genuine whole owners allocated before PrefixPlan. Their - // bytes are already in Context::allocated_bytes, charged once. - cache.routed_outputs = - Some(Rc::new(super::super::cache_routed_outputs::RoutedOutputBank::new(binding.identity(), context)?)); - if cache.routed_outputs.as_ref().ok_or(Error::IdentityMismatch)?.allocated_bytes() != 37_273_600 { - return Err(Error::IdentityMismatch); - } - let maximum = std::array::from_fn(|role| template.iter().map(|keys| keys[role].bytes).max().unwrap_or(0)); - cache.ephemeral_routed = Some(Rc::new(RefCell::new(if mapped { - super::super::cache_ephemeral_routed::EphemeralRoutedOwner::new_mapped( - binding, - context, - maximum, - super::super::cache_ephemeral_routed::MappedStageShape::Single16, - )? - } else { - super::super::cache_ephemeral_routed::EphemeralRoutedOwner::new(binding, context, maximum)? - }))); - let ephemeral_charge = maximum - .into_iter() - .try_fold(if mapped { 36usize } else { 0 }, |n, b| n.checked_add(b).ok_or(Error::Overflow))? - .checked_mul(if mapped { 16 } else { 2 }) - .ok_or(Error::Overflow)?; - if cache - .ephemeral_routed - .as_ref() - .ok_or(Error::IdentityMismatch)? - .try_borrow() - .map_err(|_| Error::IdentityMismatch)? - .allocated_bytes() - != ephemeral_charge - { - return Err(Error::IdentityMismatch); - } - let mut shared = cache_profile::SharedPermanentPool::new(shared_keys)?; - let baseline = cache.counters; - 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 window_spill = profile_window_spill_with_floor(1usize << 30)?; - let spill = window_spill.checked_add(largest).ok_or(Error::Overflow)?; - // Only the permanent192 descriptor map survives. No second routed - // HashMap/LRU representation competes with the actual slot map. - cache.main.try_reserve(shared.descriptor_count()).map_err(|_| Error::InputAllocation)?; - let buckets = cache - .main - .capacity() - .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 = profile - .metadata_bytes() - .checked_add(shared.metadata_bytes()?) - .and_then(|n| n.checked_add(cache.routed_outputs.as_ref()?.metadata_bytes())) - .and_then(|n| n.checked_add(cache.ephemeral_routed.as_ref()?.try_borrow().ok()?.metadata_bytes())) - .and_then(|n| n.checked_add(map_bytes)) - .and_then(|n| n.checked_add(cache.lru.as_ref()?.metadata_bytes().ok()?)) - .and_then(|n| n.checked_add(bytes.len())) - .ok_or(Error::Overflow)?; - // Prove the COMPLETE adaptive allocation bound before first shared - // H2D, not after the remaining physical memory became tight. - let (free, _) = context.memory_info().map_err(driver_error)?; - let before = cache_strata_adaptive::AdaptivePolicy::new( - &profile, - template, - ProfileLimits { - main_cap: remaining_main, - allocated: context.allocated_bytes().checked_add(shared.bytes).ok_or(Error::Overflow)?, - device_budget: context.budget_bytes(), - physical_free: free.checked_sub(shared.bytes).ok_or(Error::InputAllocation)?, - working_reserve: WORKING_RESERVE, - window_spill, - }, - )?; - let adaptive_metadata = before - .metadata_bytes() - .checked_add(before.initial_slots().len() * std::mem::size_of::; 3]>>()) - .and_then(|n| n.checked_add(cache_strata_adaptive::transfer_metadata_bound())) - .and_then(|n| n.checked_add(metadata)) - .ok_or(Error::Overflow)?; - if adaptive_metadata > HOST_CAP { - return Err(Error::InputAllocation); - } - drop(before); - // Persistent15-worker stacks/coordinator/fixed scratch belong to - // the model source lifetime, not every request's CPU job budget. - cpu_budget::admit_pool(binding, adaptive_metadata)?; - let cpu = super::super::super::cpu_expert_miss::CpuMissWorkspace::new(binding, 15) - .map_err(super::super::super::cpu_expert_miss::runtime_error)?; - if cpu.workers() != 15 { - return Err(Error::IdentityMismatch); - } - cache.cpu_miss = Some(Rc::new(RefCell::new(cpu))); - for layer in 0..48 { - cache.preload_shared_quartet(binding, shared.quartet(layer)?, spill, &mut shared)?; - } - if cache.main_bytes != shared.bytes || cache.main.len() != 192 { - return Err(Error::IdentityMismatch); - } - shared.finish_preload(); - let (free, _) = context.memory_info().map_err(driver_error)?; - let owner = cache_strata_adaptive::AdaptiveCache::preload( - binding, - context, - &profile, - template, - ProfileLimits { - main_cap: remaining_main, - allocated: context.allocated_bytes(), - device_budget: context.budget_bytes(), - physical_free: free, - working_reserve: WORKING_RESERVE, - window_spill, - }, - shared.bytes, - metadata, - )?; - let Some(main_bytes) = cache.main_bytes.checked_add(owner.charged_bytes()) else { - let _ = owner.close(); - return Err(Error::Overflow); - }; - cache.adaptive_shared = Some(shared); - cache.adaptive = Some(owner); - cache.main_bytes = main_bytes; - let shared = cache.strata_adaptive_shared_witness()?; - if shared.descriptors != 192 || !shared.successful_bytes_reconcile { - return Err(Error::IdentityMismatch); - } - cache.validate(binding, context) - })(); - if let Err(primary) = operation { + if let Err(primary) = cache.build_adaptive(binding, context, &profile, bytes.len(), mapped) { let _ = cache.close(); return Err(primary); } Ok(cache) } + + fn build_adaptive( + &mut self, + binding: &ModelBinding, + context: &'ctx Context<'ctx>, + profile: &RankedProfile, + profile_len: usize, + mapped: bool, + ) -> Result<()> { + self.adaptive_precheck(binding, context)?; + let (template, shared_keys, largest) = adaptive_template(binding)?; + self.adaptive_outputs(binding, context, &template, mapped)?; + let mut shared = self.adaptive_shared_pool(shared_keys)?; + let plan = self.adaptive_plan(profile, profile_len, &mut shared, largest, template)?; + let adaptive_metadata = self.adaptive_admit(context, profile, &plan, &shared)?; + // Persistent15-worker stacks/coordinator/fixed scratch belong to + // the model source lifetime, not every request's CPU job budget. + self.adaptive_cpu_pool(binding, adaptive_metadata)?; + self.adaptive_preload(binding, context, profile, plan, shared) + } + + fn adaptive_precheck(&mut self, binding: &ModelBinding, context: &'ctx Context<'ctx>) -> Result<()> { + self.validate(binding, context)?; + let required = 46_612usize.checked_add(WORKING_RESERVE).ok_or(Error::Overflow)?; + let (free, _) = context.memory_info().map_err(driver_error)?; + if free < required || context.allocated_bytes().checked_add(required).is_none_or(|n| n > context.budget_bytes()) + { + return Err(Error::InputAllocation); + } + self.routed_resident = Some(Rc::new(super::super::RoutedResidentOwner::new(context)?)); + self.admit_mtp_input_workspace(binding) + } + + /// These are genuine whole owners allocated before PrefixPlan. Their bytes are already in + /// Context::allocated_bytes, charged once. + fn adaptive_outputs( + &mut self, + binding: &ModelBinding, + context: &'ctx Context<'ctx>, + template: &[[MoeWeightDescriptor; 3]; 48], + mapped: bool, + ) -> Result<()> { + let bank = super::super::cache_routed_outputs::RoutedOutputBank::new(binding.identity(), context)?; + self.routed_outputs = Some(Rc::new(bank)); + if self.routed_outputs.as_ref().ok_or(Error::IdentityMismatch)?.allocated_bytes() != 37_273_600 { + return Err(Error::IdentityMismatch); + } + let maximum = std::array::from_fn(|role| template.iter().map(|keys| keys[role].bytes).max().unwrap_or(0)); + self.adaptive_ephemeral(binding, context, maximum, mapped) + } + + fn adaptive_ephemeral( + &mut self, + binding: &ModelBinding, + context: &'ctx Context<'ctx>, + maximum: [usize; 3], + mapped: bool, + ) -> Result<()> { + use super::super::cache_ephemeral_routed::{EphemeralRoutedOwner, MappedStageShape}; + let owner = if mapped { + EphemeralRoutedOwner::new_mapped(binding, context, maximum, MappedStageShape::Single16)? + } else { + EphemeralRoutedOwner::new(binding, context, maximum)? + }; + self.ephemeral_routed = Some(Rc::new(RefCell::new(owner))); + self.check_ephemeral_charge(maximum, mapped) + } + + fn check_ephemeral_charge(&self, maximum: [usize; 3], mapped: bool) -> Result<()> { + let ephemeral_charge = maximum + .into_iter() + .try_fold(if mapped { 36usize } else { 0 }, |n, b| n.checked_add(b).ok_or(Error::Overflow))? + .checked_mul(if mapped { 16 } else { 2 }) + .ok_or(Error::Overflow)?; + let owner = self.ephemeral_routed.as_ref().ok_or(Error::IdentityMismatch)?; + if owner.try_borrow().map_err(|_| Error::IdentityMismatch)?.allocated_bytes() != ephemeral_charge { + return Err(Error::IdentityMismatch); + } + Ok(()) + } + + fn adaptive_shared_pool( + &self, + shared_keys: Vec<[MoeWeightDescriptor; 4]>, + ) -> Result { + let mut shared = cache_profile::SharedPermanentPool::new(shared_keys)?; + let baseline = self.counters; + shared.baseline = + [baseline.hits, baseline.misses, baseline.read_bytes, baseline.upload_bytes, baseline.eviction_bytes]; + Ok(shared) + } + + /// Only the permanent192 descriptor map survives. No second routed HashMap/LRU representation competes with + /// the actual slot map. + fn adaptive_plan( + &mut self, + profile: &RankedProfile, + profile_len: usize, + shared: &mut cache_profile::SharedPermanentPool, + largest: usize, + template: [[MoeWeightDescriptor; 3]; 48], + ) -> Result { + let remaining_main = cache_profile::remaining_shared_main(MAIN_LIMIT, shared.bytes)?; + let window_spill = profile_window_spill_with_floor(1usize << 30)?; + let spill = window_spill.checked_add(largest).ok_or(Error::Overflow)?; + self.main.try_reserve(shared.descriptor_count()).map_err(|_| Error::InputAllocation)?; + let metadata = self.adaptive_host_metadata(profile, profile_len, shared)?; + Ok(AdaptivePlan { template, remaining_main, window_spill, spill, metadata }) + } + + fn adaptive_host_metadata( + &self, + profile: &RankedProfile, + profile_len: usize, + shared: &cache_profile::SharedPermanentPool, + ) -> Result { + let buckets = self.main.capacity().checked_mul(4).and_then(|n| n.checked_add(2)).map(|n| n / 3); + let map_bytes = 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)?; + profile + .metadata_bytes() + .checked_add(shared.metadata_bytes()?) + .and_then(|n| n.checked_add(self.routed_outputs.as_ref()?.metadata_bytes())) + .and_then(|n| n.checked_add(self.ephemeral_routed.as_ref()?.try_borrow().ok()?.metadata_bytes())) + .and_then(|n| n.checked_add(map_bytes)) + .and_then(|n| n.checked_add(self.lru.as_ref()?.metadata_bytes().ok()?)) + .and_then(|n| n.checked_add(profile_len)) + .ok_or(Error::Overflow) + } + + /// Prove the COMPLETE adaptive allocation bound before first shared H2D, not after the remaining physical + /// memory became tight. + fn adaptive_admit( + &self, + context: &'ctx Context<'ctx>, + profile: &RankedProfile, + plan: &AdaptivePlan, + shared: &cache_profile::SharedPermanentPool, + ) -> Result { + let (free, _) = context.memory_info().map_err(driver_error)?; + let limits = ProfileLimits { + main_cap: plan.remaining_main, + allocated: context.allocated_bytes().checked_add(shared.bytes).ok_or(Error::Overflow)?, + device_budget: context.budget_bytes(), + physical_free: free.checked_sub(shared.bytes).ok_or(Error::InputAllocation)?, + working_reserve: WORKING_RESERVE, + window_spill: plan.window_spill, + }; + let before = cache_strata_adaptive::AdaptivePolicy::new(profile, plan.template, limits)?; + let adaptive_metadata = before + .metadata_bytes() + .checked_add(before.initial_slots().len() * std::mem::size_of::; 3]>>()) + .and_then(|n| n.checked_add(cache_strata_adaptive::transfer_metadata_bound())) + .and_then(|n| n.checked_add(plan.metadata)) + .ok_or(Error::Overflow)?; + if adaptive_metadata > HOST_CAP { + return Err(Error::InputAllocation); + } + Ok(adaptive_metadata) + } + + fn adaptive_cpu_pool(&mut self, binding: &ModelBinding, adaptive_metadata: usize) -> Result<()> { + cpu_budget::admit_pool(binding, adaptive_metadata)?; + let cpu = super::super::super::cpu_expert_miss::CpuMissWorkspace::new(binding, 15) + .map_err(super::super::super::cpu_expert_miss::runtime_error)?; + if cpu.workers() != 15 { + return Err(Error::IdentityMismatch); + } + self.cpu_miss = Some(Rc::new(RefCell::new(cpu))); + Ok(()) + } + + fn adaptive_preload( + &mut self, + binding: &ModelBinding, + context: &'ctx Context<'ctx>, + profile: &RankedProfile, + plan: AdaptivePlan, + mut shared: cache_profile::SharedPermanentPool, + ) -> Result<()> { + for layer in 0..48 { + self.preload_shared_quartet(binding, shared.quartet(layer)?, plan.spill, &mut shared)?; + } + if self.main_bytes != shared.bytes || self.main.len() != 192 { + return Err(Error::IdentityMismatch); + } + shared.finish_preload(); + let owner = Self::adaptive_owner(binding, context, profile, &plan, shared.bytes)?; + self.adopt_adaptive(binding, context, shared, owner) + } + + fn adaptive_owner( + binding: &ModelBinding, + context: &'ctx Context<'ctx>, + profile: &RankedProfile, + plan: &AdaptivePlan, + shared_bytes: usize, + ) -> Result> { + let (free, _) = context.memory_info().map_err(driver_error)?; + let limits = ProfileLimits { + main_cap: plan.remaining_main, + allocated: context.allocated_bytes(), + device_budget: context.budget_bytes(), + physical_free: free, + working_reserve: WORKING_RESERVE, + window_spill: plan.window_spill, + }; + cache_strata_adaptive::AdaptiveCache::preload( + binding, + context, + profile, + plan.template, + limits, + shared_bytes, + plan.metadata, + ) + } + + fn adopt_adaptive( + &mut self, + binding: &ModelBinding, + context: &'ctx Context<'ctx>, + shared: cache_profile::SharedPermanentPool, + owner: cache_strata_adaptive::AdaptiveCache<'ctx>, + ) -> Result<()> { + let Some(main_bytes) = self.main_bytes.checked_add(owner.charged_bytes()) else { + let _ = owner.close(); + return Err(Error::Overflow); + }; + self.adaptive_shared = Some(shared); + self.adaptive = Some(owner); + self.main_bytes = main_bytes; + let shared = self.strata_adaptive_shared_witness()?; + if shared.descriptors != 192 || !shared.successful_bytes_reconcile { + return Err(Error::IdentityMismatch); + } + self.validate(binding, context) + } +} + +/// The fixed inputs of one adaptive build once the shared pool is sized. +struct AdaptivePlan { + template: [[MoeWeightDescriptor; 3]; 48], + remaining_main: usize, + window_spill: usize, + spill: usize, + metadata: usize, +} + +type SharedKeys = Vec<[MoeWeightDescriptor; 4]>; + +/// The first-expert Gate/Up/Down descriptor of every layer, the shared descriptors and the largest layer footprint. +fn adaptive_template(binding: &ModelBinding) -> Result<([[MoeWeightDescriptor; 3]; 48], SharedKeys, usize)> { + 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 largest = 0usize; + for layer in 0..48 { + let keys = [ + binding.moe_preload_descriptor(layer, 0, MoeMatrixRole::Gate).map_err(binding_error)?, + binding.moe_preload_descriptor(layer, 0, MoeMatrixRole::Up).map_err(binding_error)?, + binding.moe_preload_descriptor(layer, 0, MoeMatrixRole::Down).map_err(binding_error)?, + ]; + largest = largest.max(keys.iter().try_fold(0usize, |n, k| n.checked_add(k.bytes).ok_or(Error::Overflow))?); + layer_keys.push(keys); + shared_keys.push(binding.moe_shared_preload_descriptors(layer).map_err(binding_error)?); + } + let template = layer_keys.try_into().map_err(|_| Error::InvalidDimension)?; + Ok((template, shared_keys, largest)) }