Skip to main content

oa/ml/nn/
moe.gen.rs

1// @generated by tool/gen/nn/generate.py; DO NOT EDIT.
2// Source: tool/gen/nn/schema/ml/ml_nn_moe.json
3// generator_version=8; schema_sha256=0cc78fa439dd2b385acdc3f373b1aa679e5a94ed540eeb1cb0c0c7d91b76c8d2
4
5use std::{
6	cell::{Cell, RefCell},
7	rc::Rc,
8};
9
10use crate::{DType, Error, Matrix, Result, Runtime, matrix as core_matrix};
11
12use super::super::{Module, ModuleRegistry, NamedBuffer, Parameter, autograd, matrix, random};
13
14use super::{Linear, RmsNorm, Swiglu};
15
16// OA donor: oacpp/source/cpp/lib/oa/ml/nn/moe/moe.cpp
17// Adaptation: Complete donor sparse routing, stacked parameter ownership, shared experts, balancing losses and reduced host telemetry; Rust retains deterministic seeded host initialization, versioned parameter adjoints, scalar auxiliary loss and dense per-expert accumulation instead of donor concat storage
18/// Reduced host telemetry for the latest MoE routing decision.
19#[derive(Clone, Debug, PartialEq)]
20pub struct MoeRouteStats {
21	load_fraction: Vec<f32>,
22	mean_probability: Vec<f32>,
23	entropy: f32,
24	max_load_ratio: f32,
25	dead_experts: usize,
26}
27
28impl MoeRouteStats {
29	/// Return the fraction of token-slot assignments received by each expert.
30	pub fn load_fraction(&self) -> &[f32] {
31		&self.load_fraction
32	}
33
34	/// Return the mean unbiased router probability for each expert.
35	pub fn mean_probability(&self) -> &[f32] {
36		&self.mean_probability
37	}
38
39	/// Return normalized load entropy in `[0, 1]` (`1` is balanced).
40	pub const fn entropy(&self) -> f32 {
41		self.entropy
42	}
43
44	/// Return expert count times the maximum load fraction (`1` is balanced).
45	pub const fn max_load_ratio(&self) -> f32 {
46		self.max_load_ratio
47	}
48
49	/// Return the number of experts that received no token-slot assignments.
50	pub const fn dead_experts(&self) -> usize {
51		self.dead_experts
52	}
53}
54
55/// Sparse top-k mixture-of-experts feed-forward module.
56///
57/// The implementation preserves OA's expert-major route plan and stacked
58/// parameter layout. Routing decisions remain detached while gradients flow
59/// through selected gate magnitudes, expert projections, RMSNorm, and the
60/// residual input.
61pub struct Moe {
62	model_width: usize,
63	hidden_width: usize,
64	num_experts: usize,
65	experts_per_token: usize,
66	epsilon: f32,
67	norm: Rc<RmsNorm>,
68	router: Rc<Linear>,
69	expert_gate_up_weight: Parameter,
70	expert_gate_up_bias: Parameter,
71	expert_down_weight: Parameter,
72	expert_down_bias: Parameter,
73	shared_experts: Vec<Rc<Swiglu>>,
74	routing_bias: NamedBuffer,
75	sparse_execution: Cell<bool>,
76	balance_rate: Cell<f32>,
77	aux_loss_alpha: Cell<f32>,
78	router_z_loss_beta: Cell<f32>,
79	last_aux_loss: RefCell<Matrix>,
80	zero_aux_loss: Matrix,
81	last_selection_mask: RefCell<Option<Matrix>>,
82	last_gate_probabilities: RefCell<Option<Matrix>>,
83	registry: ModuleRegistry,
84}
85
86impl Moe {
87	pub fn new_with_seed(
88		model_width: usize,
89		hidden_width: usize,
90		num_experts: usize,
91		experts_per_token: usize,
92		epsilon: f32,
93		seed: u64,
94	) -> Result<Self> {
95		Self::new_with_seed_on(
96			&Runtime::current()?,
97			model_width,
98			hidden_width,
99			num_experts,
100			experts_per_token,
101			epsilon,
102			seed,
103		)
104	}
105
106	/// Construct a deterministically initialized sparse MoE.
107	///
108	/// `experts_per_token` is clamped to `1..=num_experts`, matching OA C++.
109	/// The current GPU route planner admits at most 256 experts.
110	///
111	/// # Errors
112	///
113	/// Returns an error for zero dimensions, more than 256 experts, invalid
114	/// epsilon, shape overflow, allocation failure, or registration failure.
115	#[allow(clippy::too_many_arguments)]
116	pub fn new_with_seed_on(
117		runtime: &Runtime,
118		model_width: usize,
119		hidden_width: usize,
120		num_experts: usize,
121		experts_per_token: usize,
122		epsilon: f32,
123		seed: u64,
124	) -> Result<Self> {
125		Self::new_with_seed_and_shared_experts_on(
126			runtime,
127			model_width,
128			hidden_width,
129			num_experts,
130			experts_per_token,
131			epsilon,
132			0,
133			seed,
134		)
135	}
136
137	/// Construct a deterministic sparse MoE with always-on shared SwiGLU experts.
138	///
139	/// Shared experts consume the same normalized input as routed experts and add
140	/// their complete ungated deltas before the residual connection.
141	///
142	/// # Errors
143	///
144	/// Returns the same errors as [`Self::new_with_seed`], plus shared-expert
145	/// allocation or registration failures.
146	#[allow(
147		clippy::too_many_arguments,
148		reason = "the constructor preserves the donor MoE dimensions, policy, and seed"
149	)]
150	pub fn new_with_seed_and_shared_experts(
151		model_width: usize,
152		hidden_width: usize,
153		num_experts: usize,
154		experts_per_token: usize,
155		epsilon: f32,
156		num_shared_experts: usize,
157		seed: u64,
158	) -> Result<Self> {
159		Self::new_with_seed_and_shared_experts_on(
160			&Runtime::current()?,
161			model_width,
162			hidden_width,
163			num_experts,
164			experts_per_token,
165			epsilon,
166			num_shared_experts,
167			seed,
168		)
169	}
170
171	#[allow(clippy::too_many_arguments)]
172	pub fn new_with_seed_and_shared_experts_on(
173		runtime: &Runtime,
174		model_width: usize,
175		hidden_width: usize,
176		num_experts: usize,
177		experts_per_token: usize,
178		epsilon: f32,
179		num_shared_experts: usize,
180		seed: u64,
181	) -> Result<Self> {
182		if model_width == 0 || hidden_width == 0 || num_experts == 0 || num_experts > 256 {
183			return Err(Error::invalid_argument(
184				"MoE dimensions must be nonzero and num_experts must not exceed 256",
185			));
186		}
187		let gate_up_width = hidden_width
188			.checked_mul(2)
189			.ok_or_else(|| Error::invalid_argument("MoE gate/up width overflows usize"))?;
190		let gate_up_count = num_experts
191			.checked_mul(gate_up_width)
192			.and_then(|value| value.checked_mul(model_width))
193			.ok_or_else(|| Error::invalid_argument("MoE gate/up weight size overflows usize"))?;
194		let gate_up_bias_count = num_experts
195			.checked_mul(gate_up_width)
196			.ok_or_else(|| Error::invalid_argument("MoE gate/up bias size overflows usize"))?;
197		let down_count = num_experts
198			.checked_mul(model_width)
199			.and_then(|value| value.checked_mul(hidden_width))
200			.ok_or_else(|| Error::invalid_argument("MoE down weight size overflows usize"))?;
201		let down_bias_count = num_experts
202			.checked_mul(model_width)
203			.ok_or_else(|| Error::invalid_argument("MoE down bias size overflows usize"))?;
204		let gate_limit = (1.0_f32 / model_width as f32).sqrt();
205		let down_limit = (1.0_f32 / hidden_width as f32).sqrt();
206		let norm = Rc::new(RmsNorm::new_on(runtime, model_width, epsilon)?);
207		let router = Rc::new(Linear::new_with_seed_on(
208			runtime,
209			model_width,
210			num_experts,
211			seed,
212		)?);
213		let gate_up_weight = Matrix::new_from_f32_on(
214			runtime,
215			[num_experts, gate_up_width, model_width],
216			&random::symmetric_uniform(gate_up_count, gate_limit, seed.wrapping_add(1)),
217		)?;
218		let gate_up_bias = Matrix::new_from_f32_on(
219			runtime,
220			[num_experts, gate_up_width],
221			&vec![0.0; gate_up_bias_count],
222		)?;
223		let down_weight = Matrix::new_from_f32_on(
224			runtime,
225			[num_experts, model_width, hidden_width],
226			&random::symmetric_uniform(down_count, down_limit, seed.wrapping_add(2)),
227		)?;
228		let down_bias = Matrix::new_from_f32_on(
229			runtime,
230			[num_experts, model_width],
231			&vec![0.0; down_bias_count],
232		)?;
233		let mut shared_experts = Vec::with_capacity(num_shared_experts);
234		for index in 0..num_shared_experts {
235			let index = u64::try_from(index)
236				.map_err(|_| Error::resource_exhausted("shared expert index exceeds u64"))?;
237			shared_experts.push(Rc::new(Swiglu::new_with_seed_on(
238				runtime,
239				model_width,
240				hidden_width,
241				true,
242				seed.wrapping_add(3).wrapping_add(index.wrapping_mul(3)),
243			)?));
244		}
245		Self::new_from_parts(
246			norm,
247			router,
248			gate_up_weight,
249			gate_up_bias,
250			down_weight,
251			down_bias,
252			experts_per_token,
253			shared_experts,
254		)
255	}
256
257	/// Construct a sparse MoE from exact donor-layout FP32 matrices.
258	///
259	/// # Errors
260	///
261	/// Returns an error unless the matrices form `norm[D]`, router weight
262	/// `[E,D]`, router bias `[E]`, gate/up weight `[E,2H,D]`, gate/up bias
263	/// `[E,2H]`, down weight `[E,D,H]`, and down bias `[E,D]` on one runtime.
264	#[allow(
265		clippy::too_many_arguments,
266		reason = "the constructor exposes the exact seven-matrix donor checkpoint layout"
267	)]
268	pub fn new_from_matrices(
269		norm_weight: Matrix,
270		router_weight: Matrix,
271		router_bias: Matrix,
272		gate_up_weight: Matrix,
273		gate_up_bias: Matrix,
274		down_weight: Matrix,
275		down_bias: Matrix,
276		experts_per_token: usize,
277		epsilon: f32,
278	) -> Result<Self> {
279		let norm = Rc::new(RmsNorm::new_from_matrix(norm_weight, epsilon)?);
280		let router = Rc::new(Linear::new_from_matrices(router_weight, router_bias)?);
281		Self::new_from_parts(
282			norm,
283			router,
284			gate_up_weight,
285			gate_up_bias,
286			down_weight,
287			down_bias,
288			experts_per_token,
289			Vec::new(),
290		)
291	}
292
293	#[allow(
294		clippy::too_many_arguments,
295		reason = "the owner retains the exact stacked donor parameter set"
296	)]
297	fn new_from_parts(
298		norm: Rc<RmsNorm>,
299		router: Rc<Linear>,
300		gate_up_weight: Matrix,
301		gate_up_bias: Matrix,
302		down_weight: Matrix,
303		down_bias: Matrix,
304		experts_per_token: usize,
305		shared_experts: Vec<Rc<Swiglu>>,
306	) -> Result<Self> {
307		let model_width = norm.dimension();
308		let num_experts = router.output_features();
309		let norm_value = norm.weight().data();
310		let router_weight = router.weight().data();
311		let router_bias = router
312			.bias()
313			.expect("MoE router is constructed with a trainable bias")
314			.data();
315		let [gate_experts, gate_up_width, gate_input] = gate_up_weight.shape() else {
316			return Err(Error::invalid_argument(
317				"MoE gate/up weight must have shape [E, 2H, D]",
318			));
319		};
320		if gate_up_width % 2 != 0 {
321			return Err(Error::invalid_argument(
322				"MoE gate/up output width must be even",
323			));
324		}
325		let hidden_width = gate_up_width / 2;
326		if num_experts == 0
327			|| num_experts > 256
328			|| router.input_features() != model_width
329			|| *gate_experts != num_experts
330			|| *gate_input != model_width
331			|| hidden_width == 0
332			|| gate_up_bias.shape() != [num_experts, *gate_up_width]
333			|| down_weight.shape() != [num_experts, model_width, hidden_width]
334			|| down_bias.shape() != [num_experts, model_width]
335			|| [
336				&router_weight,
337				&router_bias,
338				&gate_up_weight,
339				&gate_up_bias,
340				&down_weight,
341				&down_bias,
342			]
343			.iter()
344			.any(|matrix| matrix.dtype() != DType::F32 || !norm_value.runtime().same_as(matrix.runtime()))
345		{
346			return Err(Error::invalid_argument(
347				"MoE matrices do not match the donor stacked expert layout on one runtime",
348			));
349		}
350		let experts_per_token = experts_per_token.clamp(1, num_experts);
351		let expert_gate_up_weight = Parameter::new("expert_gate_up_weight", gate_up_weight)?;
352		let expert_gate_up_bias = Parameter::new("expert_gate_up_bias", gate_up_bias)?;
353		let expert_down_weight = Parameter::new("expert_down_weight", down_weight)?;
354		let expert_down_bias = Parameter::new("expert_down_bias", down_bias)?;
355		let mut registry = ModuleRegistry::new();
356		registry.register_parameter("expert_gate_up_weight", expert_gate_up_weight.clone())?;
357		registry.register_parameter("expert_gate_up_bias", expert_gate_up_bias.clone())?;
358		registry.register_parameter("expert_down_weight", expert_down_weight.clone())?;
359		registry.register_parameter("expert_down_bias", expert_down_bias.clone())?;
360		registry.register_module("norm", norm.clone())?;
361		registry.register_module("router", router.clone())?;
362		for (index, expert) in shared_experts.iter().enumerate() {
363			if expert.input_features() != model_width || expert.intermediate_size() != hidden_width {
364				return Err(Error::invalid_argument(
365					"shared MoE expert dimensions do not match the routed experts",
366				));
367			}
368			for parameter in expert.all_parameters()? {
369				if !norm_value.runtime().same_as(parameter.data().runtime()) {
370					return Err(Error::invalid_argument(
371						"shared MoE experts must belong to the routed expert runtime",
372					));
373				}
374			}
375			registry.register_module(format!("shared_expert_{index}"), expert.clone())?;
376		}
377		registry.register_buffer(
378			"routing_bias",
379			Matrix::new_from_slice_handle(
380				norm_value.runtime(),
381				vec![1, num_experts],
382				&vec![0.0; num_experts],
383			)?,
384			true,
385		)?;
386		let routing_bias = registry
387			.buffer_handle("routing_bias")
388			.ok_or_else(|| Error::internal("MoE routing-bias registration was lost"))?;
389		let zero_aux_loss = Matrix::new_from_slice_handle(norm_value.runtime(), vec![], &[0.0_f32])?;
390		Ok(Self {
391			model_width,
392			hidden_width,
393			num_experts,
394			experts_per_token,
395			epsilon: norm.epsilon(),
396			norm,
397			router,
398			expert_gate_up_weight,
399			expert_gate_up_bias,
400			expert_down_weight,
401			expert_down_bias,
402			shared_experts,
403			routing_bias,
404			sparse_execution: Cell::new(true),
405			balance_rate: Cell::new(0.0),
406			aux_loss_alpha: Cell::new(0.0),
407			router_z_loss_beta: Cell::new(0.0),
408			last_aux_loss: RefCell::new(zero_aux_loss.clone()),
409			zero_aux_loss,
410			last_selection_mask: RefCell::new(None),
411			last_gate_probabilities: RefCell::new(None),
412			registry,
413		})
414	}
415
416	/// Apply top-k routed experts and add their delta to the input.
417	///
418	/// # Errors
419	///
420	/// Returns an error unless `input` is nonempty F32 `[T,D]` on this module's
421	/// runtime, or a routing, projection, activation, or recording operation fails.
422	pub fn forward(&self, input: &Matrix) -> Result<Matrix> {
423		let [tokens, width] = input.shape() else {
424			return Err(Error::invalid_argument("MoE input must have shape [T, D]"));
425		};
426		if *tokens == 0 || *width != self.model_width || input.dtype() != DType::F32 {
427			return Err(Error::invalid_argument(
428				"MoE input must be nonempty F32 [T, model_width]",
429			));
430		}
431		let normalized = self.norm.forward(input)?;
432		let logits = self.router.forward(&normalized)?;
433		let probabilities = core_matrix::softmax(&logits, 1)?;
434		let selection_logits = if self.balance_rate.get() > 0.0 {
435			core_matrix::add(&logits, &self.routing_bias.data())?
436		} else {
437			logits.clone()
438		};
439		let top_k = core_matrix::top_k(&selection_logits, self.experts_per_token as i32, 1)?;
440		let selection_mask = core_matrix::top_k_mask(&top_k.indices, self.num_experts)?;
441		let mut delta = if self.sparse_execution.get() {
442			let route_gate = matrix::moe_route_weights(&probabilities, &top_k.indices)?;
443			let plan = core_matrix::moe_expert_plan(&top_k.indices, self.num_experts)?;
444			let packed = matrix::moe_gather(&normalized, &plan.packed_token, &plan.inverse)?;
445			let gate_up = self.grouped_projection(
446				&packed,
447				&self.expert_gate_up_weight,
448				&self.expert_gate_up_bias,
449				&plan.offsets,
450			)?;
451			let hidden = matrix::silu_mul(&gate_up, self.hidden_width)?;
452			let packed_output = self.grouped_projection(
453				&hidden,
454				&self.expert_down_weight,
455				&self.expert_down_bias,
456				&plan.offsets,
457			)?;
458			matrix::moe_combine(
459				&packed_output,
460				&route_gate,
461				&plan.inverse,
462				&plan.packed_slot,
463			)?
464		} else {
465			let gate_unnormalized = core_matrix::mul(&probabilities, &selection_mask)?;
466			let denominator = core_matrix::sum(&gate_unnormalized, 1)?;
467			let gate = core_matrix::mul(&gate_unnormalized, &core_matrix::reciprocal(&denominator)?)?;
468			self.dense_expert_delta(&normalized, &gate)?
469		};
470		for shared_expert in &self.shared_experts {
471			delta = core_matrix::add(&delta, &shared_expert.forward(&normalized)?)?;
472		}
473		let mut aux_loss = None;
474		if self.aux_loss_alpha.get() > 0.0 {
475			let reciprocal_tokens = 1.0 / *tokens as f32;
476			let load_fraction =
477				core_matrix::scale(&core_matrix::sum(&selection_mask, 0)?, reciprocal_tokens)?;
478			let mean_probability =
479				core_matrix::scale(&core_matrix::sum(&probabilities, 0)?, reciprocal_tokens)?;
480			let per_expert = core_matrix::mul(&load_fraction, &mean_probability)?;
481			let total = core_matrix::sum(&per_expert, 1)?;
482			aux_loss = Some(core_matrix::scale(
483				&total,
484				self.aux_loss_alpha.get() * self.num_experts as f32 / self.experts_per_token as f32,
485			)?);
486		}
487		if self.router_z_loss_beta.get() > 0.0 {
488			let log_probabilities = core_matrix::log_softmax(&logits, 1)?;
489			let first_logit = core_matrix::slice(&logits, 1, 0, 1)?;
490			let first_log_probability = core_matrix::slice(&log_probabilities, 1, 0, 1)?;
491			let log_sum_exp = core_matrix::sub(&first_logit, &first_log_probability)?;
492			let squared = core_matrix::mul(&log_sum_exp, &log_sum_exp)?;
493			let mean = core_matrix::scale(&core_matrix::sum(&squared, 0)?, 1.0 / *tokens as f32)?;
494			let z_loss = core_matrix::scale(&mean, self.router_z_loss_beta.get())?;
495			aux_loss = Some(if let Some(switch_loss) = aux_loss {
496				core_matrix::add(&switch_loss, &z_loss)?
497			} else {
498				z_loss
499			});
500		}
501		let aux_loss = if let Some(aux_loss) = aux_loss {
502			core_matrix::reshape(&aux_loss, Vec::new())?
503		} else {
504			self.zero_aux_loss.clone()
505		};
506		*self.last_selection_mask.borrow_mut() = Some(selection_mask);
507		*self.last_gate_probabilities.borrow_mut() = Some(probabilities);
508		*self.last_aux_loss.borrow_mut() = aux_loss;
509		core_matrix::add(input, &delta)
510	}
511
512	fn dense_expert_delta(&self, input: &Matrix, gate: &Matrix) -> Result<Matrix> {
513		for parameter in [
514			&self.expert_gate_up_weight,
515			&self.expert_gate_up_bias,
516			&self.expert_down_weight,
517			&self.expert_down_bias,
518		] {
519			autograd::record_parameter_leaf(parameter)?;
520		}
521		let gate_up_weight = self.expert_gate_up_weight.data();
522		let gate_up_bias = self.expert_gate_up_bias.data();
523		let down_weight = self.expert_down_weight.data();
524		let down_bias = self.expert_down_bias.data();
525		let mut combined = None;
526		for expert in 0..self.num_experts {
527			let start = i64::try_from(expert)
528				.map_err(|_| Error::resource_exhausted("MoE expert index exceeds i64"))?;
529			let end = start + 1;
530			let expert_gate_up_weight = core_matrix::slice(&gate_up_weight, 0, start, end)?
531				.reshape([2 * self.hidden_width, self.model_width])?;
532			let expert_gate_up_bias =
533				core_matrix::slice(&gate_up_bias, 0, start, end)?.reshape([2 * self.hidden_width])?;
534			let expert_down_weight = core_matrix::slice(&down_weight, 0, start, end)?
535				.reshape([self.model_width, self.hidden_width])?;
536			let expert_down_bias =
537				core_matrix::slice(&down_bias, 0, start, end)?.reshape([self.model_width])?;
538			let gate_up = core_matrix::add(
539				&core_matrix::matmul(input, &expert_gate_up_weight)?,
540				&expert_gate_up_bias,
541			)?;
542			let hidden = matrix::silu_mul(&gate_up, self.hidden_width)?;
543			let output = core_matrix::add(
544				&core_matrix::matmul(&hidden, &expert_down_weight)?,
545				&expert_down_bias,
546			)?;
547			let expert_gate = core_matrix::slice(gate, 1, start, end)?;
548			let weighted = core_matrix::mul(&output, &expert_gate)?;
549			combined = Some(if let Some(previous) = combined {
550				core_matrix::add(&previous, &weighted)?
551			} else {
552				weighted
553			});
554		}
555		combined.ok_or_else(|| Error::internal("MoE dense oracle has no experts"))
556	}
557
558	fn grouped_projection(
559		&self,
560		input: &Matrix,
561		weight: &Parameter,
562		bias: &Parameter,
563		offsets: &Matrix,
564	) -> Result<Matrix> {
565		let (weight_value, weight_version, _) = weight.snapshot();
566		let (bias_value, bias_version, _) = bias.snapshot();
567		matrix::grouped_linear_m_parameterized(
568			input,
569			(weight.clone(), weight_value, weight_version),
570			(bias.clone(), bias_value, bias_version),
571			offsets,
572		)
573	}
574
575	/// Return the residual model width.
576	pub const fn model_width(&self) -> usize {
577		self.model_width
578	}
579
580	/// Return the expert hidden width.
581	pub const fn hidden_width(&self) -> usize {
582		self.hidden_width
583	}
584
585	/// Return the routed expert count.
586	pub const fn num_experts(&self) -> usize {
587		self.num_experts
588	}
589
590	/// Return the clamped routes selected per token.
591	pub const fn experts_per_token(&self) -> usize {
592		self.experts_per_token
593	}
594
595	/// Select sparse grouped execution or the dense all-expert correctness oracle.
596	///
597	/// Sparse execution is enabled by default. Dense execution evaluates every
598	/// expert and exists for differential correctness testing, not performance.
599	pub fn set_sparse_execution(&self, sparse: bool) {
600		self.sparse_execution.set(sparse);
601	}
602
603	/// Return whether grouped sparse expert execution is selected.
604	pub fn sparse_execution(&self) -> bool {
605		self.sparse_execution.get()
606	}
607
608	/// Return the number of always-on shared SwiGLU experts.
609	pub fn num_shared_experts(&self) -> usize {
610		self.shared_experts.len()
611	}
612
613	/// Return the RMSNorm epsilon.
614	pub const fn epsilon(&self) -> f32 {
615		self.epsilon
616	}
617
618	/// Set the auxiliary-loss-free routing-bias update rate.
619	///
620	/// Non-finite or non-positive values disable balancing, matching the donor's
621	/// clamped opt-in policy.
622	pub fn set_balance_rate(&self, gamma: f32) {
623		self.balance_rate.set(if gamma.is_finite() && gamma > 0.0 {
624			gamma
625		} else {
626			0.0
627		});
628	}
629
630	/// Return the current auxiliary-loss-free routing-bias update rate.
631	pub fn balance_rate(&self) -> f32 {
632		self.balance_rate.get()
633	}
634
635	/// Return the persistent device-resident `[1, E]` routing-bias buffer.
636	pub fn routing_bias(&self) -> Matrix {
637		self.routing_bias.data()
638	}
639
640	/// Set the Switch/GShard routing auxiliary-loss coefficient.
641	///
642	/// Non-finite or non-positive values disable the loss. The default is zero,
643	/// so the module's established forward and gradient graph remain unchanged.
644	pub fn set_aux_loss_alpha(&self, alpha: f32) {
645		self
646			.aux_loss_alpha
647			.set(if alpha.is_finite() && alpha > 0.0 {
648				alpha
649			} else {
650				0.0
651			});
652	}
653
654	/// Return the current Switch/GShard auxiliary-loss coefficient.
655	pub fn aux_loss_alpha(&self) -> f32 {
656		self.aux_loss_alpha.get()
657	}
658
659	/// Set the router z-loss coefficient.
660	///
661	/// Non-finite or non-positive values disable the loss. The donor objective is
662	/// `beta * mean(logsumexp(router_logits)^2)` and is evaluated through a stable
663	/// LogSoftmax identity.
664	pub fn set_router_z_loss_beta(&self, beta: f32) {
665		self
666			.router_z_loss_beta
667			.set(if beta.is_finite() && beta > 0.0 {
668				beta
669			} else {
670				0.0
671			});
672	}
673
674	/// Return the current router z-loss coefficient.
675	pub fn router_z_loss_beta(&self) -> f32 {
676		self.router_z_loss_beta.get()
677	}
678
679	/// Return the scalar auxiliary loss recorded by the latest forward.
680	///
681	/// Add this value to the task loss before [`crate::ml::GradientTape::backward`].
682	/// Before the first forward, and after a forward while the coefficient is
683	/// disabled, this returns a stable zero scalar.
684	pub fn aux_loss(&self) -> Matrix {
685		self.last_aux_loss.borrow().clone()
686	}
687
688	/// Queue one routing-bias update from the latest selection mask.
689	///
690	/// This method does not submit, wait, or read the bias on the host. It is a
691	/// no-op while balancing is disabled or before the first forward.
692	///
693	/// # Errors
694	///
695	/// Returns an error when the device-resident update cannot be recorded.
696	pub fn update_routing_bias(&self) -> Result<()> {
697		let gamma = self.balance_rate.get();
698		let Some(selection_mask) = self.last_selection_mask() else {
699			return Ok(());
700		};
701		if gamma == 0.0 {
702			return Ok(());
703		}
704		core_matrix::moe_routing_bias_update(
705			&selection_mask,
706			&self.routing_bias.data(),
707			self.experts_per_token,
708			gamma,
709		)
710	}
711
712	/// Return the selection mask from the latest recorded forward, if any.
713	pub fn last_selection_mask(&self) -> Option<Matrix> {
714		self.last_selection_mask.borrow().clone()
715	}
716
717	/// Return router probabilities from the latest recorded forward, if any.
718	pub fn last_gate_probabilities(&self) -> Option<Matrix> {
719		self.last_gate_probabilities.borrow().clone()
720	}
721
722	/// Reduce and read routing telemetry from the latest forward.
723	///
724	/// This is an explicit host-observation boundary. It reads only two reduced
725	/// `[E]` vectors; it never transfers the token-by-expert routing matrices.
726	/// Before the first forward, all per-expert values and aggregate statistics
727	/// are zero.
728	///
729	/// # Errors
730	///
731	/// Returns an error when reduction, submission, completion, or readback fails.
732	pub fn route_stats(&self) -> Result<MoeRouteStats> {
733		let Some(selection_mask) = self.last_selection_mask() else {
734			return Ok(MoeRouteStats {
735				load_fraction: vec![0.0; self.num_experts],
736				mean_probability: vec![0.0; self.num_experts],
737				entropy: 0.0,
738				max_load_ratio: 0.0,
739				dead_experts: self.num_experts,
740			});
741		};
742		let probabilities = self
743			.last_gate_probabilities()
744			.expect("selection mask and gate probabilities are committed together");
745		let load = core_matrix::sum(&selection_mask, 0)?.reshape([self.num_experts])?;
746		let probability_sum = core_matrix::sum(&probabilities, 0)?.reshape([self.num_experts])?;
747		let mut load_fraction = load.read_f32()?;
748		let mut mean_probability = probability_sum.read_f32()?;
749		let load_total = load_fraction
750			.iter()
751			.map(|value| f64::from(*value))
752			.sum::<f64>();
753		if load_total > 0.0 {
754			for value in &mut load_fraction {
755				*value = (f64::from(*value) / load_total) as f32;
756			}
757		}
758		let tokens = probabilities.shape()[0] as f32;
759		for value in &mut mean_probability {
760			*value /= tokens;
761		}
762		let mut entropy = 0.0_f64;
763		let mut max_load = 0.0_f64;
764		let mut dead_experts = 0;
765		for &fraction in &load_fraction {
766			let fraction = f64::from(fraction);
767			if fraction > 0.0 {
768				entropy -= fraction * fraction.ln();
769			} else {
770				dead_experts += 1;
771			}
772			max_load = max_load.max(fraction);
773		}
774		let entropy = if self.num_experts > 1 {
775			(entropy / (self.num_experts as f64).ln()) as f32
776		} else {
777			1.0
778		};
779		Ok(MoeRouteStats {
780			load_fraction,
781			mean_probability,
782			entropy,
783			max_load_ratio: (max_load * self.num_experts as f64) as f32,
784			dead_experts,
785		})
786	}
787
788	/// Return the stacked routed-expert gate/up weight.
789	pub fn expert_gate_up_weight(&self) -> Parameter {
790		self.expert_gate_up_weight.clone()
791	}
792
793	/// Return the stacked routed-expert gate/up bias.
794	pub fn expert_gate_up_bias(&self) -> Parameter {
795		self.expert_gate_up_bias.clone()
796	}
797
798	/// Return the stacked routed-expert down-projection weight.
799	pub fn expert_down_weight(&self) -> Parameter {
800		self.expert_down_weight.clone()
801	}
802
803	/// Return the stacked routed-expert down-projection bias.
804	pub fn expert_down_bias(&self) -> Parameter {
805		self.expert_down_bias.clone()
806	}
807}
808
809impl Module for Moe {
810	fn forward(&self, input: &Matrix) -> Result<Matrix> {
811		Moe::forward(self, input)
812	}
813
814	fn registry(&self) -> &ModuleRegistry {
815		&self.registry
816	}
817}