1use 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#[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 pub fn load_fraction(&self) -> &[f32] {
31 &self.load_fraction
32 }
33
34 pub fn mean_probability(&self) -> &[f32] {
36 &self.mean_probability
37 }
38
39 pub const fn entropy(&self) -> f32 {
41 self.entropy
42 }
43
44 pub const fn max_load_ratio(&self) -> f32 {
46 self.max_load_ratio
47 }
48
49 pub const fn dead_experts(&self) -> usize {
51 self.dead_experts
52 }
53}
54
55pub 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 #[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 #[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 #[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 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 pub const fn model_width(&self) -> usize {
577 self.model_width
578 }
579
580 pub const fn hidden_width(&self) -> usize {
582 self.hidden_width
583 }
584
585 pub const fn num_experts(&self) -> usize {
587 self.num_experts
588 }
589
590 pub const fn experts_per_token(&self) -> usize {
592 self.experts_per_token
593 }
594
595 pub fn set_sparse_execution(&self, sparse: bool) {
600 self.sparse_execution.set(sparse);
601 }
602
603 pub fn sparse_execution(&self) -> bool {
605 self.sparse_execution.get()
606 }
607
608 pub fn num_shared_experts(&self) -> usize {
610 self.shared_experts.len()
611 }
612
613 pub const fn epsilon(&self) -> f32 {
615 self.epsilon
616 }
617
618 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 pub fn balance_rate(&self) -> f32 {
632 self.balance_rate.get()
633 }
634
635 pub fn routing_bias(&self) -> Matrix {
637 self.routing_bias.data()
638 }
639
640 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 pub fn aux_loss_alpha(&self) -> f32 {
656 self.aux_loss_alpha.get()
657 }
658
659 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 pub fn router_z_loss_beta(&self) -> f32 {
676 self.router_z_loss_beta.get()
677 }
678
679 pub fn aux_loss(&self) -> Matrix {
685 self.last_aux_loss.borrow().clone()
686 }
687
688 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 pub fn last_selection_mask(&self) -> Option<Matrix> {
714 self.last_selection_mask.borrow().clone()
715 }
716
717 pub fn last_gate_probabilities(&self) -> Option<Matrix> {
719 self.last_gate_probabilities.borrow().clone()
720 }
721
722 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 pub fn expert_gate_up_weight(&self) -> Parameter {
790 self.expert_gate_up_weight.clone()
791 }
792
793 pub fn expert_gate_up_bias(&self) -> Parameter {
795 self.expert_gate_up_bias.clone()
796 }
797
798 pub fn expert_down_weight(&self) -> Parameter {
800 self.expert_down_weight.clone()
801 }
802
803 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}