interplane.Get Omega
Read in your language

aien-sovereign-core-mv

AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.

Brought by drakestapleton

branch main Branches Tags History

aien-sovereign-core-mv / crates / aien-expert-residency / src / budget.rs

198 lines · 7022 bytes Raw Blame History
1//! The memory ledger: fixed reservations first, expert slots from what is
2//! left.
3//!
4//! The plan is computed once and does not change while the manager runs, so
5//! the committed total is also the high-water mark of the plan. Live usage
6//! (resident and in-flight bytes) is tracked by the manager and is always at
7//! or below the corresponding reservation.
8
9use crate::error::BudgetError;
10
11/// Shape of the model attention KV cache at the configured maximum context.
12/// This is the persisted-attention KV, a different object from expert
13/// weights; it is budgeted here only so expert slots cannot eat into it.
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub struct KvShape {
16 pub layers: u32,
17 pub kv_heads: u32,
18 pub head_dim: u32,
19 pub bytes_per_element: u32,
20 pub max_context_tokens: u32,
21 pub max_sequences: u32,
22}
23
24impl KvShape {
25 /// Bytes for K and V of every layer, KV head, position and sequence.
26 pub fn bytes(&self) -> Result<u64, BudgetError> {
27 [
28 2,
29 u64::from(self.layers),
30 u64::from(self.kv_heads),
31 u64::from(self.head_dim),
32 u64::from(self.bytes_per_element),
33 u64::from(self.max_context_tokens),
34 u64::from(self.max_sequences),
35 ]
36 .iter()
37 .try_fold(1u64, |acc, &f| acc.checked_mul(f))
38 .ok_or(BudgetError::Overflow { what: "kv cache" })
39 }
40}
41
42/// What the machine has and what must be set aside before any expert slot.
43#[derive(Debug, Clone, Copy, PartialEq, Eq)]
44pub struct MemoryBudget {
45 /// Total unified memory the plan may describe.
46 pub total_bytes: u64,
47 /// OS, driver and resource-manager safety headroom. Never allocated.
48 pub safety_headroom_bytes: u64,
49 /// Resident non-expert weights (embeddings, attention, norms, router,
50 /// any experts kept permanently resident outside the cache).
51 pub non_expert_weight_bytes: u64,
52 /// Attention KV cache shape.
53 pub kv: KvShape,
54 /// Activations and kernel workspace.
55 pub scratch_bytes: u64,
56 /// NVMe read staging buffers. Bytes in flight are charged here.
57 pub staging_bytes: u64,
58}
59
60/// A ledger category.
61#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
62pub enum Category {
63 SafetyHeadroom,
64 NonExpertWeights,
65 KvCache,
66 Scratch,
67 Staging,
68 ExpertPool,
69}
70
71/// The computed plan. Every byte of `total_bytes` is in exactly one field:
72/// the five reservations, the expert pool or `unassigned_bytes`.
73#[derive(Debug, Clone, Copy, PartialEq, Eq)]
74pub struct Ledger {
75 pub total_bytes: u64,
76 pub safety_headroom_bytes: u64,
77 pub non_expert_weight_bytes: u64,
78 pub kv_cache_bytes: u64,
79 pub scratch_bytes: u64,
80 pub staging_bytes: u64,
81 pub slot_bytes: u64,
82 pub slot_count: u32,
83 /// `slot_count * slot_bytes`.
84 pub expert_pool_bytes: u64,
85 /// Left over: less than one slot, or above `max_slots`. Not allocated.
86 pub unassigned_bytes: u64,
87}
88
89/// What the runtime actually allocated, per category (from the allocator or
90/// the driver's report).
91#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
92pub struct AllocationReport {
93 pub non_expert_weight_bytes: u64,
94 pub kv_cache_bytes: u64,
95 pub scratch_bytes: u64,
96 pub staging_bytes: u64,
97 pub expert_pool_bytes: u64,
98}
99
100impl Ledger {
101 /// Reserve the fixed categories, then cut the remainder into whole slots
102 /// of `slot_bytes`, at most `max_slots` of them.
103 pub fn plan(
104 budget: &MemoryBudget,
105 slot_bytes: u64,
106 max_slots: Option<u32>,
107 ) -> Result<Self, BudgetError> {
108 if slot_bytes == 0 {
109 return Err(BudgetError::ZeroSlotBytes);
110 }
111 let kv_cache_bytes = budget.kv.bytes()?;
112 let required = [
113 budget.safety_headroom_bytes,
114 budget.non_expert_weight_bytes,
115 kv_cache_bytes,
116 budget.scratch_bytes,
117 budget.staging_bytes,
118 ]
119 .iter()
120 .try_fold(0u64, |acc, &b| acc.checked_add(b))
121 .ok_or(BudgetError::Overflow {
122 what: "fixed reservations",
123 })?;
124 if required > budget.total_bytes {
125 return Err(BudgetError::Oversubscribed {
126 required,
127 total: budget.total_bytes,
128 });
129 }
130 let available = budget.total_bytes - required;
131 let fit = available / slot_bytes;
132 let mut slot_count = u32::try_from(fit).unwrap_or(u32::MAX);
133 if let Some(cap) = max_slots {
134 slot_count = slot_count.min(cap);
135 }
136 if slot_count == 0 {
137 return Err(BudgetError::NoExpertSlots {
138 available_bytes: available,
139 slot_bytes,
140 });
141 }
142 // Cannot overflow: slot_count * slot_bytes <= available.
143 let expert_pool_bytes = u64::from(slot_count) * slot_bytes;
144 Ok(Self {
145 total_bytes: budget.total_bytes,
146 safety_headroom_bytes: budget.safety_headroom_bytes,
147 non_expert_weight_bytes: budget.non_expert_weight_bytes,
148 kv_cache_bytes,
149 scratch_bytes: budget.scratch_bytes,
150 staging_bytes: budget.staging_bytes,
151 slot_bytes,
152 slot_count,
153 expert_pool_bytes,
154 unassigned_bytes: available - expert_pool_bytes,
155 })
156 }
157
158 /// Everything reserved, including the expert pool. Excludes only
159 /// `unassigned_bytes`. Fixed for the life of the plan.
160 pub fn committed_bytes(&self) -> u64 {
161 self.total_bytes - self.unassigned_bytes
162 }
163
164 /// The reservation for one category.
165 pub fn reserved(&self, category: Category) -> u64 {
166 match category {
167 Category::SafetyHeadroom => self.safety_headroom_bytes,
168 Category::NonExpertWeights => self.non_expert_weight_bytes,
169 Category::KvCache => self.kv_cache_bytes,
170 Category::Scratch => self.scratch_bytes,
171 Category::Staging => self.staging_bytes,
172 Category::ExpertPool => self.expert_pool_bytes,
173 }
174 }
175
176 /// Check a real allocation report against the plan. Every category must
177 /// be at or below its reservation; the first one over is returned.
178 pub fn check_allocations(&self, report: &AllocationReport) -> Result<(), BudgetError> {
179 let rows = [
180 (Category::NonExpertWeights, report.non_expert_weight_bytes),
181 (Category::KvCache, report.kv_cache_bytes),
182 (Category::Scratch, report.scratch_bytes),
183 (Category::Staging, report.staging_bytes),
184 (Category::ExpertPool, report.expert_pool_bytes),
185 ];
186 for (category, actual) in rows {
187 let reserved = self.reserved(category);
188 if actual > reserved {
189 return Err(BudgetError::AllocationExceedsReservation {
190 category,
191 reserved,
192 actual,
193 });
194 }
195 }
196 Ok(())
197 }
198}