STRA-338 params h04: shared-permanent profile build (profile file/request, pool seed, quartet room, pinned source) takes grouped operands

This commit is contained in:
Pavlo Ratushnyi
2026-11-08 01:26:24 +01:00
parent 32ceea0fd9
commit d2d8f17ebd
5 changed files with 91 additions and 48 deletions
@@ -10,6 +10,11 @@ struct PinnedLayouts {
charges: [usize; 3],
extra: usize,
}
/// The raw source blocks of one pinned triplet and the total number of bytes read for them.
struct PinnedSource<'a> {
raw: &'a [Box<[u8]>; 3],
read_bytes: usize,
}
struct PinnedAdmission {
layouts: [Option<(leleka_cuda_driver::MmqFormat, usize)>; 3],
charges: [usize; 3],
@@ -37,7 +42,7 @@ impl<'ctx> MoeWeightCache<'ctx> {
self.discard_owned(owned);
return Err(primary);
}
self.commit_pinned_triplet(&admission, keys, owned, &raw, read_bytes);
self.commit_pinned_triplet(&admission, keys, owned, PinnedSource { raw: &raw, read_bytes });
Ok(())
}
fn admit_pinned_triplet(&self, keys: &[MoeWeightDescriptor; 3]) -> Result<PinnedAdmission> {
@@ -153,9 +158,9 @@ impl<'ctx> MoeWeightCache<'ctx> {
admission: &PinnedAdmission,
keys: [MoeWeightDescriptor; 3],
owned: [Option<EncodedWeight<'ctx>>; 3],
raw: &[Box<[u8]>; 3],
read_bytes: usize,
source: PinnedSource<'_>,
) {
let PinnedSource { raw, read_bytes } = source;
let PinnedAdmission { layouts, charges, extra, next_bytes, next_age, next_loaded } = *admission;
// Capacity, complete ownership, byte/age/count arithmetic checked above.
// No fallible work or allocation follows the first triplet insertion.
@@ -2,9 +2,18 @@
#[allow(unused_imports)]
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
use super::profile_build_fns::ProfileKind;
use super::profile_build_fns::{ProfileFile, ProfileKind, ProfileRequest};
use super::*;
/// The room a shared quartet upload must leave free: the spill allowance and the main pool size once the quartet is
/// inserted.
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
#[derive(Clone, Copy)]
struct QuartetRoom {
spill: usize,
next_bytes: usize,
}
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
impl<'ctx> MoeWeightCache<'ctx> {
/// Separately selected only: all target shared weights precede the ranked prefix.
@@ -16,7 +25,8 @@ impl<'ctx> MoeWeightCache<'ctx> {
) -> Result<Self> {
let profile = RankedProfile::parse(bytes, PROFILE_SHA)?;
let mut cache = Self::new_native_integer_iq3_mmq_retained_mtp_kv_shared_tail_lru(binding, context)?;
if let Err(primary) = cache.build_profile(binding, context, &profile, bytes.len(), ProfileKind::Fixed) {
let file = ProfileFile { profile: &profile, size_bytes: bytes.len() };
if let Err(primary) = cache.build_profile(binding, context, ProfileRequest { file, kind: ProfileKind::Fixed }) {
let _ = cache.close();
return Err(primary);
}
@@ -31,7 +41,8 @@ impl<'ctx> MoeWeightCache<'ctx> {
) -> Result<()> {
let (next_bytes, next_age) = self.admit_shared_quartet(binding, &keys, shared)?;
let mut owned: [Option<EncodedWeight<'ctx>>; 4] = std::array::from_fn(|_| None);
if let Err(primary) = self.upload_shared_quartet(binding, &keys, spill, next_bytes, &mut owned) {
if let Err(primary) = self.upload_shared_quartet(binding, &keys, QuartetRoom { spill, next_bytes }, &mut owned)
{
self.discard_owned(owned);
return Err(primary);
}
@@ -72,10 +83,10 @@ impl<'ctx> MoeWeightCache<'ctx> {
&mut self,
binding: &ModelBinding,
keys: &[MoeWeightDescriptor; 4],
spill: usize,
next_bytes: usize,
room: QuartetRoom,
owned: &mut [Option<EncodedWeight<'ctx>>; 4],
) -> Result<()> {
let QuartetRoom { spill, next_bytes } = room;
// Each role keeps its complete spill/headroom admission before source
// read or allocation; no previous permanent weight may be evicted.
for (index, key) in keys.iter().copied().enumerate() {
@@ -2,7 +2,7 @@
#[allow(unused_imports)]
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
use super::profile_build_fns::ProfileKind;
use super::profile_build_fns::{ProfileFile, ProfileKind, ProfileRequest};
use super::*;
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
@@ -16,7 +16,9 @@ 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)?;
if let Err(primary) = cache.build_profile(binding, context, &profile, bytes.len(), ProfileKind::Learned) {
let file = ProfileFile { profile: &profile, size_bytes: bytes.len() };
if let Err(primary) = cache.build_profile(binding, context, ProfileRequest { file, kind: ProfileKind::Learned })
{
let _ = cache.close();
return Err(primary);
}
@@ -1,6 +1,7 @@
//! Moved out of the parent module by STRA-338: impl MoeWeightCache.
#[allow(unused_imports)]
use super::profile_build_fns::ProfileFile;
use super::*;
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
@@ -34,7 +35,8 @@ 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)?;
if let Err(primary) = cache.build_adaptive(binding, context, &profile, bytes.len(), mapped) {
let file = ProfileFile { profile: &profile, size_bytes: bytes.len() };
if let Err(primary) = cache.build_adaptive(binding, context, file, mapped) {
let _ = cache.close();
return Err(primary);
}
@@ -45,20 +47,19 @@ impl<'ctx> MoeWeightCache<'ctx> {
&mut self,
binding: &ModelBinding,
context: &'ctx Context<'ctx>,
profile: &RankedProfile,
profile_len: usize,
file: ProfileFile<'_>,
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)?;
let plan = self.adaptive_plan(file, &mut shared, largest, template)?;
let adaptive_metadata = self.adaptive_admit(context, file.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)
self.adaptive_preload(binding, file.profile, plan, shared)
}
fn adaptive_precheck(&mut self, binding: &ModelBinding, context: &'ctx Context<'ctx>) -> Result<()> {
@@ -136,8 +137,7 @@ impl<'ctx> MoeWeightCache<'ctx> {
/// the actual slot map.
fn adaptive_plan(
&mut self,
profile: &RankedProfile,
profile_len: usize,
file: ProfileFile<'_>,
shared: &mut cache_profile::SharedPermanentPool,
largest: usize,
template: [[MoeWeightDescriptor; 3]; 48],
@@ -146,7 +146,7 @@ impl<'ctx> MoeWeightCache<'ctx> {
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)?;
let metadata = self.adaptive_host_metadata(file.profile, file.size_bytes, shared)?;
Ok(AdaptivePlan { template, remaining_main, window_spill, spill, metadata })
}
@@ -218,11 +218,12 @@ impl<'ctx> MoeWeightCache<'ctx> {
fn adaptive_preload(
&mut self,
binding: &ModelBinding,
context: &'ctx Context<'ctx>,
profile: &RankedProfile,
plan: AdaptivePlan,
mut shared: cache_profile::SharedPermanentPool,
) -> Result<()> {
// The context already validated against this cache by the adaptive precheck.
let context = self.context;
for layer in 0..48 {
self.preload_shared_quartet(binding, shared.quartet(layer)?, plan.spill, &mut shared)?;
}
@@ -14,6 +14,35 @@ pub(super) enum ProfileKind {
Learned,
}
/// The parsed ranked profile with the byte size of the file it came from, which is charged as host metadata.
#[derive(Clone, Copy)]
pub(super) struct ProfileFile<'a> {
pub(super) profile: &'a RankedProfile,
pub(super) size_bytes: usize,
}
/// A profile to build the shared-permanent cache from: the file and which sizing and seeding to use.
#[derive(Clone, Copy)]
pub(super) struct ProfileRequest<'a> {
pub(super) file: ProfileFile<'a>,
pub(super) kind: ProfileKind,
}
/// The shared permanent pool with the counters at the moment it was sized: what the pinned pool starts from.
struct SharedPoolSeed {
pool: cache_profile::SharedPermanentPool,
baseline: WeightCacheCounters,
}
/// The byte limits that bound the metadata slot count: what is left of the main pool, the spill reserve and the
/// smallest per-layer charge.
#[derive(Clone, Copy)]
struct MainPoolBounds {
remaining_main: usize,
spill: usize,
minimum_layer_charge: usize,
}
type LayerKeys = Vec<[MoeWeightDescriptor; 3]>;
type SharedKeys = Vec<[MoeWeightDescriptor; 4]>;
@@ -39,20 +68,19 @@ impl<'ctx> MoeWeightCache<'ctx> {
&mut self,
binding: &ModelBinding,
context: &'ctx Context<'ctx>,
profile: &RankedProfile,
bytes_len: usize,
kind: ProfileKind,
request: ProfileRequest<'_>,
) -> Result<()> {
let (layers, mut shared, baseline) = self.profile_open(binding, context)?;
let budget = self.profile_budget(kind, profile, bytes_len, &layers, &shared)?;
let ProfileRequest { file, kind } = request;
let (layers, mut seed) = self.profile_open(binding, context)?;
let budget = self.profile_budget(request, &layers, &seed.pool)?;
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)?;
self.profile_preload_shared(binding, &mut seed.pool, budget.spill)?;
let expected_bytes = self.profile_pin(file.profile, &layers, seed, budget)?;
self.profile_preload_pinned(binding, file.profile, &layers.layer_keys, expected_bytes)?;
if kind == ProfileKind::Learned {
self.seed_learned_main()?;
}
@@ -64,7 +92,7 @@ impl<'ctx> MoeWeightCache<'ctx> {
&mut self,
binding: &ModelBinding,
context: &'ctx Context<'ctx>,
) -> Result<(ProfileLayers, cache_profile::SharedPermanentPool, WeightCacheCounters)> {
) -> Result<(ProfileLayers, SharedPoolSeed)> {
self.validate(binding, context)?;
self.admit_mtp_input_workspace(binding)?;
let baseline = self.counters;
@@ -72,7 +100,7 @@ impl<'ctx> MoeWeightCache<'ctx> {
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))
Ok((layers, SharedPoolSeed { pool: shared, baseline }))
}
fn profile_layers(&self, binding: &ModelBinding) -> Result<ProfileLayers> {
@@ -98,9 +126,7 @@ impl<'ctx> MoeWeightCache<'ctx> {
fn profile_budget(
&mut self,
kind: ProfileKind,
profile: &RankedProfile,
bytes_len: usize,
request: ProfileRequest<'_>,
layers: &ProfileLayers,
shared: &cache_profile::SharedPermanentPool,
) -> Result<ProfileBudget> {
@@ -109,24 +135,24 @@ impl<'ctx> MoeWeightCache<'ctx> {
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)?;
let bounds = MainPoolBounds { remaining_main, spill, minimum_layer_charge: minimum };
let maximum_count = profile_maximum(request, &layers.charges, bounds, 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())?;
let metadata_bytes = self.profile_metadata(request, 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,
request: ProfileRequest<'_>,
layers: &ProfileLayers,
shared: &cache_profile::SharedPermanentPool,
selected_capacity: usize,
) -> Result<usize> {
let ProfileRequest { file: ProfileFile { profile, size_bytes }, kind } = request;
let map_bytes = self.main_map_bytes()?;
let learned_extra = if kind == ProfileKind::Learned {
std::mem::size_of::<Self>() + std::mem::size_of::<[usize; 144]>()
@@ -139,7 +165,7 @@ impl<'ctx> MoeWeightCache<'ctx> {
.and_then(|n| n.checked_add(selected_capacity * std::mem::size_of::<bool>()))
.and_then(|n| n.checked_add(std::mem::size_of::<PrefixPlan>()))
.and_then(|n| n.checked_add(std::mem::size_of::<PinnedPool>()))
.and_then(|n| n.checked_add(bytes_len))
.and_then(|n| n.checked_add(size_bytes))
.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))
@@ -179,14 +205,13 @@ impl<'ctx> MoeWeightCache<'ctx> {
/// 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,
seed: SharedPoolSeed,
budget: ProfileBudget,
baseline: WeightCacheCounters,
) -> Result<usize> {
let limits = profile_limits(context, budget.remaining_main, budget.window_spill)?;
let SharedPoolSeed { pool: shared, baseline } = seed;
let limits = profile_limits(self.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) {
@@ -286,14 +311,13 @@ fn charge_extremes(charges: &[[usize; 3]; 48]) -> Result<(usize, usize)> {
/// Metadata slot bound for the fixed prefix or the learned main residency, plus the shared descriptors.
fn profile_maximum(
kind: ProfileKind,
profile: &RankedProfile,
request: ProfileRequest<'_>,
charges: &[[usize; 3]; 48],
remaining_main: usize,
spill: usize,
minimum: usize,
bounds: MainPoolBounds,
shared: &cache_profile::SharedPermanentPool,
) -> Result<usize> {
let ProfileRequest { file: ProfileFile { profile, .. }, kind } = request;
let MainPoolBounds { remaining_main, spill, minimum_layer_charge: minimum } = bounds;
if kind == ProfileKind::Learned {
return cache_profile::learned_main_slot_bound(charges, remaining_main)?
.checked_add(shared.descriptor_count())