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
aien-sovereign-core-mv / crates / aien-inference-abi / src / moe_plan.rs
| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright 2026 Drake Stapleton (AIEN / aien-dev) |
| 3 | // |
| 4 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | // you may not use this file except in compliance with the License. |
| 6 | // You may obtain a copy of the License at |
| 7 | // |
| 8 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | // |
| 10 | // Unless required by applicable law or agreed to in writing, software |
| 11 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | // See the License for the specific language governing permissions and |
| 14 | // limitations under the License. |
| 15 | |
| 16 | //! Branch-agnostic MoE routing plan for Qwen3-Coder-30B-A3B. |
| 17 | //! |
| 18 | //! This is the host-side correctness oracle and batch metadata contract for |
| 19 | //! the routed expert layer (`qwen3_moe` CPU oracle, Omega GB10 path). Expert GEMMs consume assignments in grouped order; |
| 20 | //! the inverse map restores each token's original top-k slots. |
| 21 | |
| 22 | use std::fmt; |
| 23 | |
| 24 | pub const QWEN3_CODER_A3B_EXPERTS: usize = 128; |
| 25 | pub const QWEN3_CODER_A3B_TOP_K: usize = 8; |
| 26 | |
| 27 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 28 | pub enum MoePlanError { |
| 29 | InvalidShape, |
| 30 | InvalidLogit { token: usize, expert: usize }, |
| 31 | InvalidExpertOutput, |
| 32 | } |
| 33 | |
| 34 | impl fmt::Display for MoePlanError { |
| 35 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 36 | match self { |
| 37 | Self::InvalidShape => write!(f, "invalid MoE routing shape"), |
| 38 | Self::InvalidLogit { token, expert } => { |
| 39 | write!( |
| 40 | f, |
| 41 | "non-finite router logit at token {token}, expert {expert}" |
| 42 | ) |
| 43 | } |
| 44 | Self::InvalidExpertOutput => write!(f, "invalid grouped expert output shape"), |
| 45 | } |
| 46 | } |
| 47 | } |
| 48 | |
| 49 | impl std::error::Error for MoePlanError {} |
| 50 | |
| 51 | /// Assignment offsets and maps use u32, the index width of the device routing ABI. |
| 52 | #[derive(Debug, Clone, PartialEq)] |
| 53 | pub struct MoeBatchPlan { |
| 54 | pub tokens: usize, |
| 55 | pub experts: usize, |
| 56 | pub top_k: usize, |
| 57 | /// Expert ID for each token-major assignment, length `tokens * top_k`. |
| 58 | pub topk_experts: Vec<u32>, |
| 59 | /// Normalized probability for each token-major assignment. |
| 60 | pub topk_weights: Vec<f32>, |
| 61 | /// Prefix sum of assignment counts by expert, length `experts + 1`. |
| 62 | pub expert_offsets: Vec<u32>, |
| 63 | /// Token-major assignment index at each grouped position. |
| 64 | pub grouped_to_assignment: Vec<u32>, |
| 65 | /// Grouped position of each token-major assignment. |
| 66 | pub assignment_to_grouped: Vec<u32>, |
| 67 | /// Token ID at each grouped position for gathering activations. |
| 68 | pub grouped_token_ids: Vec<u32>, |
| 69 | } |
| 70 | |
| 71 | #[derive(Debug, Clone, PartialEq)] |
| 72 | pub struct MoeRoutingTelemetry { |
| 73 | pub tokens_per_expert: Vec<u32>, |
| 74 | pub experts_touched: usize, |
| 75 | pub expert_batch_p50: u32, |
| 76 | pub expert_batch_p95: u32, |
| 77 | pub max_expert_batch: u32, |
| 78 | /// Shannon entropy of expert assignment frequency, in bits. |
| 79 | pub routing_entropy_bits: f64, |
| 80 | } |
| 81 | |
| 82 | impl MoeBatchPlan { |
| 83 | /// Softmax in FP32, top-k, then renormalize selected probabilities. |
| 84 | /// This matches Qwen3-MoE's `norm_topk_prob=true` routing semantics. |
| 85 | /// Ties use the lower expert ID so the host plan is deterministic. |
| 86 | pub fn from_logits( |
| 87 | logits: &[f32], |
| 88 | tokens: usize, |
| 89 | experts: usize, |
| 90 | top_k: usize, |
| 91 | ) -> Result<Self, MoePlanError> { |
| 92 | if experts == 0 |
| 93 | || top_k == 0 |
| 94 | || top_k > experts |
| 95 | || tokens > u32::MAX as usize / top_k |
| 96 | || logits.len() |
| 97 | != tokens |
| 98 | .checked_mul(experts) |
| 99 | .ok_or(MoePlanError::InvalidShape)? |
| 100 | { |
| 101 | return Err(MoePlanError::InvalidShape); |
| 102 | } |
| 103 | |
| 104 | let assignments = tokens * top_k; |
| 105 | let mut topk_experts = Vec::with_capacity(assignments); |
| 106 | let mut topk_weights = Vec::with_capacity(assignments); |
| 107 | let mut counts = vec![0u32; experts]; |
| 108 | let mut ranking: Vec<usize> = (0..experts).collect(); |
| 109 | |
| 110 | for (token, row) in logits.chunks_exact(experts).enumerate() { |
| 111 | for (expert, value) in row.iter().enumerate() { |
| 112 | if !value.is_finite() { |
| 113 | return Err(MoePlanError::InvalidLogit { token, expert }); |
| 114 | } |
| 115 | } |
| 116 | ranking.sort_unstable_by(|&a, &b| row[b].total_cmp(&row[a]).then(a.cmp(&b))); |
| 117 | let max_logit = row[ranking[0]]; |
| 118 | // The common full-softmax denominator cancels during top-k |
| 119 | // renormalization, so only the selected exponentials are needed. |
| 120 | let mut selected = [0.0f32; QWEN3_CODER_A3B_TOP_K]; |
| 121 | let mut sum = 0.0f32; |
| 122 | for slot in 0..top_k { |
| 123 | let probability = (row[ranking[slot]] - max_logit).exp(); |
| 124 | if top_k <= selected.len() { |
| 125 | selected[slot] = probability; |
| 126 | } |
| 127 | sum += probability; |
| 128 | } |
| 129 | for slot in 0..top_k { |
| 130 | let expert = ranking[slot]; |
| 131 | topk_experts.push(expert as u32); |
| 132 | let probability = if top_k <= selected.len() { |
| 133 | selected[slot] |
| 134 | } else { |
| 135 | (row[expert] - max_logit).exp() |
| 136 | }; |
| 137 | topk_weights.push(probability / sum); |
| 138 | counts[expert] += 1; |
| 139 | } |
| 140 | } |
| 141 | |
| 142 | let mut expert_offsets = Vec::with_capacity(experts + 1); |
| 143 | expert_offsets.push(0u32); |
| 144 | for count in counts { |
| 145 | expert_offsets.push(expert_offsets.last().unwrap() + count); |
| 146 | } |
| 147 | let mut cursor = expert_offsets[..experts].to_vec(); |
| 148 | let mut grouped_to_assignment = vec![0u32; assignments]; |
| 149 | let mut assignment_to_grouped = vec![0u32; assignments]; |
| 150 | let mut grouped_token_ids = vec![0u32; assignments]; |
| 151 | for assignment in 0..assignments { |
| 152 | let expert = topk_experts[assignment] as usize; |
| 153 | let grouped = cursor[expert] as usize; |
| 154 | cursor[expert] += 1; |
| 155 | grouped_to_assignment[grouped] = assignment as u32; |
| 156 | assignment_to_grouped[assignment] = grouped as u32; |
| 157 | grouped_token_ids[grouped] = (assignment / top_k) as u32; |
| 158 | } |
| 159 | |
| 160 | Ok(Self { |
| 161 | tokens, |
| 162 | experts, |
| 163 | top_k, |
| 164 | topk_experts, |
| 165 | topk_weights, |
| 166 | expert_offsets, |
| 167 | grouped_to_assignment, |
| 168 | assignment_to_grouped, |
| 169 | grouped_token_ids, |
| 170 | }) |
| 171 | } |
| 172 | |
| 173 | pub fn qwen3_coder_a3b(logits: &[f32], tokens: usize) -> Result<Self, MoePlanError> { |
| 174 | Self::from_logits( |
| 175 | logits, |
| 176 | tokens, |
| 177 | QWEN3_CODER_A3B_EXPERTS, |
| 178 | QWEN3_CODER_A3B_TOP_K, |
| 179 | ) |
| 180 | } |
| 181 | |
| 182 | pub fn telemetry(&self) -> MoeRoutingTelemetry { |
| 183 | let tokens_per_expert: Vec<u32> = self |
| 184 | .expert_offsets |
| 185 | .windows(2) |
| 186 | .map(|window| window[1] - window[0]) |
| 187 | .collect(); |
| 188 | let mut active: Vec<u32> = tokens_per_expert |
| 189 | .iter() |
| 190 | .copied() |
| 191 | .filter(|&count| count > 0) |
| 192 | .collect(); |
| 193 | active.sort_unstable(); |
| 194 | let total = (self.tokens * self.top_k) as f64; |
| 195 | let entropy = if total == 0.0 { |
| 196 | 0.0 |
| 197 | } else { |
| 198 | active.iter().fold(0.0, |acc, count| { |
| 199 | let p = *count as f64 / total; |
| 200 | acc - p * p.log2() |
| 201 | }) |
| 202 | }; |
| 203 | let percentile = |p: usize| -> u32 { |
| 204 | if active.is_empty() { |
| 205 | 0 |
| 206 | } else { |
| 207 | active[((active.len() - 1) * p).div_ceil(100)] |
| 208 | } |
| 209 | }; |
| 210 | MoeRoutingTelemetry { |
| 211 | tokens_per_expert, |
| 212 | experts_touched: active.len(), |
| 213 | expert_batch_p50: percentile(50), |
| 214 | expert_batch_p95: percentile(95), |
| 215 | max_expert_batch: active.last().copied().unwrap_or(0), |
| 216 | routing_entropy_bits: entropy, |
| 217 | } |
| 218 | } |
| 219 | |
| 220 | /// Reference weighted inverse permutation for device parity checks. |
| 221 | pub fn reduce_grouped( |
| 222 | &self, |
| 223 | grouped_output: &[f32], |
| 224 | hidden: usize, |
| 225 | ) -> Result<Vec<f32>, MoePlanError> { |
| 226 | if hidden == 0 || grouped_output.len() != self.tokens * self.top_k * hidden { |
| 227 | return Err(MoePlanError::InvalidExpertOutput); |
| 228 | } |
| 229 | let mut output = vec![0.0f32; self.tokens * hidden]; |
| 230 | for assignment in 0..self.tokens * self.top_k { |
| 231 | let grouped = self.assignment_to_grouped[assignment] as usize; |
| 232 | let token = assignment / self.top_k; |
| 233 | let weight = self.topk_weights[assignment]; |
| 234 | for channel in 0..hidden { |
| 235 | output[token * hidden + channel] += |
| 236 | grouped_output[grouped * hidden + channel] * weight; |
| 237 | } |
| 238 | } |
| 239 | Ok(output) |
| 240 | } |
| 241 | } |
| 242 | |
| 243 | #[cfg(test)] |
| 244 | mod tests { |
| 245 | use super::*; |
| 246 | |
| 247 | #[test] |
| 248 | fn qwen_routing_groups_and_restores_all_assignments() { |
| 249 | let mut logits = vec![-20.0f32; 3 * QWEN3_CODER_A3B_EXPERTS]; |
| 250 | for token in 0..3 { |
| 251 | for slot in 0..QWEN3_CODER_A3B_TOP_K { |
| 252 | logits[token * QWEN3_CODER_A3B_EXPERTS + (token * 11 + slot)] = (slot + 1) as f32; |
| 253 | } |
| 254 | } |
| 255 | let plan = MoeBatchPlan::qwen3_coder_a3b(&logits, 3).unwrap(); |
| 256 | assert_eq!(plan.expert_offsets[QWEN3_CODER_A3B_EXPERTS], 24); |
| 257 | for assignment in 0..24 { |
| 258 | let grouped = plan.assignment_to_grouped[assignment] as usize; |
| 259 | assert_eq!(plan.grouped_to_assignment[grouped], assignment as u32); |
| 260 | assert_eq!(plan.grouped_token_ids[grouped], (assignment / 8) as u32); |
| 261 | let expert = plan.topk_experts[assignment] as usize; |
| 262 | assert!(grouped >= plan.expert_offsets[expert] as usize); |
| 263 | assert!(grouped < plan.expert_offsets[expert + 1] as usize); |
| 264 | } |
| 265 | for weights in plan.topk_weights.chunks_exact(8) { |
| 266 | assert!((weights.iter().sum::<f32>() - 1.0).abs() < 1e-6); |
| 267 | } |
| 268 | } |
| 269 | |
| 270 | #[test] |
| 271 | fn weighted_inverse_permutation_preserves_token_values() { |
| 272 | let plan = MoeBatchPlan::from_logits(&[4.0, 2.0, 1.0, 2.0, 4.0, 1.0], 2, 3, 2).unwrap(); |
| 273 | let mut grouped = vec![0.0; 4 * 2]; |
| 274 | for (position, token) in plan.grouped_token_ids.iter().enumerate() { |
| 275 | grouped[position * 2] = (*token + 1) as f32; |
| 276 | grouped[position * 2 + 1] = (*token + 1) as f32 * 3.0; |
| 277 | } |
| 278 | let output = plan.reduce_grouped(&grouped, 2).unwrap(); |
| 279 | for (actual, expected) in output.iter().zip([1.0, 3.0, 2.0, 6.0]) { |
| 280 | assert!((actual - expected).abs() < 1e-6); |
| 281 | } |
| 282 | } |
| 283 | |
| 284 | #[test] |
| 285 | fn five_hundred_branch_batch_exposes_expert_histogram() { |
| 286 | let logits: Vec<f32> = (0..500 * QWEN3_CODER_A3B_EXPERTS) |
| 287 | .map(|index| ((index * 37 + index / 128 * 19) % 257) as f32 / 32.0) |
| 288 | .collect(); |
| 289 | let plan = MoeBatchPlan::qwen3_coder_a3b(&logits, 500).unwrap(); |
| 290 | let telemetry = plan.telemetry(); |
| 291 | assert_eq!(telemetry.tokens_per_expert.iter().sum::<u32>(), 4_000); |
| 292 | assert!(telemetry.experts_touched > 100); |
| 293 | assert!(telemetry.expert_batch_p95 >= telemetry.expert_batch_p50); |
| 294 | assert!(telemetry.routing_entropy_bits > 6.0); |
| 295 | } |
| 296 | |
| 297 | #[test] |
| 298 | fn rejects_corrupt_router_values_and_shape() { |
| 299 | assert!(matches!( |
| 300 | MoeBatchPlan::from_logits(&[f32::NAN], 1, 1, 1), |
| 301 | Err(MoePlanError::InvalidLogit { .. }) |
| 302 | )); |
| 303 | assert!(matches!( |
| 304 | MoeBatchPlan::from_logits(&[1.0], 1, 2, 1), |
| 305 | Err(MoePlanError::InvalidShape) |
| 306 | )); |
| 307 | } |
| 308 | } |