1use crate::ml::Parameter;
4use crate::ml::validation::{shader_u32, validate_f32_same_runtime};
5use crate::runtime::{
6 BufferAccess, BufferBinding, ComputeDispatch, KernelId, PushConstant, RuntimeHandle,
7 SemanticDispatch,
8};
9use crate::{DType, Error, Matrix, OpAttribute, Result, Runtime};
10
11use super::optimizer::{
12 MuonParameterState, Optimizer, OptimizerCheckpoint, OptimizerRestore, checkpoint_capability,
13};
14
15#[derive(Clone, Copy)]
16pub(super) struct MuonScalars {
17 pub(super) learning_rate: f32,
18 pub(super) beta: f32,
19 pub(super) weight_decay: f32,
20 pub(super) epsilon: f32,
21 pub(super) ns5_iterations: u32,
22}
23
24#[derive(Clone, Copy)]
25enum MuonSlot {
26 Parameter,
27 Gradient,
28 Momentum,
29 Temporary(usize),
30}
31
32struct MuonStage {
33 kernel: KernelId,
34 bindings: Vec<(MuonSlot, BufferAccess)>,
35 push_constants: Vec<PushConstant>,
36 workgroups: [u32; 3],
37}
38
39fn muon(
40 parameter: &Matrix,
41 gradient: &Matrix,
42 momentum: &Matrix,
43 scalars: MuonScalars,
44) -> Result<()> {
45 const OPERATION: &str = crate::core::operation::ml::MUON.name();
46 validate_f32_same_runtime(OPERATION, &[parameter, gradient, momentum])?;
47 for candidate in [gradient, momentum] {
48 if candidate.shape() != parameter.shape() {
49 return Err(Error::invalid_argument(format!(
50 "{OPERATION} requires identical parameter, gradient, and momentum shapes"
51 )));
52 }
53 }
54 let element_count = shader_u32(parameter.num_elements(), "element count", OPERATION)?;
55 if element_count == 0 {
56 return Ok(());
57 }
58 let attributes = muon_attributes(scalars);
59 if parameter.shape().len() != 2 || scalars.ns5_iterations == 0 {
60 let buffers = [
61 BufferBinding::read_write(parameter.storage()),
62 BufferBinding::read(gradient.storage()),
63 BufferBinding::read_write(momentum.storage()),
64 ];
65 let push_constants = [
66 PushConstant::U32(element_count),
67 PushConstant::F32(scalars.learning_rate),
68 PushConstant::F32(scalars.beta),
69 PushConstant::F32(scalars.weight_decay),
70 ];
71 let kernel = KernelId::MlMuonVectorF32;
72 return {
73 let inputs: &[&Matrix] = &[parameter, gradient, momentum];
74 let outputs: &[&Matrix] = &[parameter, momentum];
75 let attributes: &[OpAttribute] = &attributes;
76 let dispatch = ComputeDispatch {
77 kernel,
78 buffers: &buffers,
79 push_constants: &push_constants,
80 workgroups: kernel.linear_workgroups(element_count),
81 indirect: None,
82 };
83 let contract = dispatch.kernel.semantic_contract().ok_or_else(|| {
84 Error::internal(format!(
85 "lowering-only kernel {} cannot own one semantic ML operation",
86 dispatch.kernel.report_name()
87 ))
88 })?;
89 let runtime = inputs
90 .first()
91 .ok_or_else(|| Error::internal("semantic ML dispatch requires an input"))?
92 .runtime();
93 runtime.record_semantic(
94 dispatch,
95 SemanticDispatch {
96 contract,
97 inputs,
98 outputs,
99 attributes,
100 },
101 )
102 };
103 }
104 let [rows, columns] = parameter.shape() else {
105 unreachable!("rank checked above")
106 };
107 let rows = shader_u32(*rows, "row count", OPERATION)?;
108 let columns = shader_u32(*columns, "column count", OPERATION)?;
109 muon_matrix(
110 parameter,
111 gradient,
112 momentum,
113 rows,
114 columns,
115 scalars,
116 &attributes,
117 )
118}
119
120fn muon_matrix(
121 parameter: &Matrix,
122 gradient: &Matrix,
123 momentum: &Matrix,
124 rows: u32,
125 columns: u32,
126 scalars: MuonScalars,
127 attributes: &[OpAttribute],
128) -> Result<()> {
129 const NS_A: f32 = 3.4445;
130 const NS_B: f32 = -4.7750;
131 const NS_C: f32 = 2.0315;
132 let count = rows
133 .checked_mul(columns)
134 .ok_or_else(|| Error::invalid_argument("ml.muon matrix size exceeds u32"))?;
135 let transposed = rows > columns;
136 let (operation_rows, operation_columns) = if transposed {
137 (columns, rows)
138 } else {
139 (rows, columns)
140 };
141 let mut temporaries = Vec::new();
142 let mut stages = Vec::new();
143 let update = allocate_muon_temp(parameter, &[rows, columns], &mut temporaries)?;
144 stages.push(MuonStage {
145 kernel: KernelId::MlMuonNesterovF32,
146 bindings: vec![
147 (MuonSlot::Gradient, BufferAccess::Read),
148 (MuonSlot::Momentum, BufferAccess::ReadWrite),
149 (update, BufferAccess::Write),
150 ],
151 push_constants: vec![PushConstant::U32(count), PushConstant::F32(scalars.beta)],
152 workgroups: KernelId::MlMuonNesterovF32.linear_workgroups(count),
153 });
154 let mut z = if transposed {
155 let transposed_update = allocate_muon_temp(
156 parameter,
157 &[operation_rows, operation_columns],
158 &mut temporaries,
159 )?;
160 stages.push(muon_transpose_stage(
161 update,
162 transposed_update,
163 rows,
164 columns,
165 ));
166 transposed_update
167 } else {
168 update
169 };
170 let norm = allocate_muon_temp(parameter, &[1], &mut temporaries)?;
171 stages.push(MuonStage {
172 kernel: KernelId::MlMuonNormalizeF32,
173 bindings: vec![
174 (z, BufferAccess::Read),
175 (z, BufferAccess::ReadWrite),
176 (norm, BufferAccess::Write),
177 ],
178 push_constants: vec![
179 PushConstant::U32(operation_rows),
180 PushConstant::U32(operation_columns),
181 PushConstant::F32(scalars.epsilon),
182 ],
183 workgroups: [1, 1, 1],
184 });
185 for _ in 0..scalars.ns5_iterations {
186 let a = allocate_muon_temp(
187 parameter,
188 &[operation_rows, operation_rows],
189 &mut temporaries,
190 )?;
191 stages.push(muon_matmul_nt_stage(
192 parameter.runtime(),
193 z,
194 z,
195 a,
196 operation_rows,
197 operation_rows,
198 operation_columns,
199 )?);
200 let next_z = allocate_muon_temp(
201 parameter,
202 &[operation_rows, operation_columns],
203 &mut temporaries,
204 )?;
205 if operation_rows <= 64 {
206 let b = allocate_muon_temp(
207 parameter,
208 &[operation_rows, operation_rows],
209 &mut temporaries,
210 )?;
211 stages.push(muon_matmul_axpby_stage(
212 a,
213 a,
214 a,
215 b,
216 operation_rows,
217 operation_rows,
218 operation_rows,
219 NS_C,
220 NS_B,
221 ));
222 stages.push(muon_matmul_axpby_stage(
223 b,
224 z,
225 z,
226 next_z,
227 operation_rows,
228 operation_columns,
229 operation_rows,
230 1.0,
231 NS_A,
232 ));
233 } else {
234 let aa = allocate_muon_temp(
235 parameter,
236 &[operation_rows, operation_rows],
237 &mut temporaries,
238 )?;
239 stages.push(muon_matmul_nt_stage(
240 parameter.runtime(),
241 a,
242 a,
243 aa,
244 operation_rows,
245 operation_rows,
246 operation_rows,
247 )?);
248 let b = allocate_muon_temp(
249 parameter,
250 &[operation_rows, operation_rows],
251 &mut temporaries,
252 )?;
253 stages.push(muon_linear_stage(
254 a,
255 aa,
256 b,
257 operation_rows * operation_rows,
258 NS_B,
259 NS_C,
260 ));
261 let z_transpose = allocate_muon_temp(
262 parameter,
263 &[operation_columns, operation_rows],
264 &mut temporaries,
265 )?;
266 stages.push(muon_transpose_stage(
267 z,
268 z_transpose,
269 operation_rows,
270 operation_columns,
271 ));
272 let bz = allocate_muon_temp(
273 parameter,
274 &[operation_rows, operation_columns],
275 &mut temporaries,
276 )?;
277 stages.push(muon_matmul_nt_stage(
278 parameter.runtime(),
279 b,
280 z_transpose,
281 bz,
282 operation_rows,
283 operation_columns,
284 operation_rows,
285 )?);
286 stages.push(muon_linear_stage(z, bz, next_z, count, NS_A, 1.0));
287 }
288 z = next_z;
289 }
290 let orthogonal = if transposed {
291 let output = allocate_muon_temp(parameter, &[rows, columns], &mut temporaries)?;
292 stages.push(muon_transpose_stage(
293 z,
294 output,
295 operation_rows,
296 operation_columns,
297 ));
298 output
299 } else {
300 z
301 };
302 stages.push(MuonStage {
303 kernel: KernelId::MlMuonApplyF32,
304 bindings: vec![
305 (MuonSlot::Parameter, BufferAccess::ReadWrite),
306 (orthogonal, BufferAccess::Read),
307 ],
308 push_constants: vec![
309 PushConstant::U32(count),
310 PushConstant::F32(scalars.learning_rate),
311 PushConstant::F32(scalars.weight_decay),
312 PushConstant::F32(0.2 * (rows.max(columns) as f32).sqrt()),
313 ],
314 workgroups: KernelId::MlMuonApplyF32.linear_workgroups(count),
315 });
316 let binding_sets = stages
317 .iter()
318 .map(|stage| {
319 stage
320 .bindings
321 .iter()
322 .map(|(slot, access)| {
323 let matrix = match slot {
324 MuonSlot::Parameter => parameter,
325 MuonSlot::Gradient => gradient,
326 MuonSlot::Momentum => momentum,
327 MuonSlot::Temporary(index) => &temporaries[*index],
328 };
329 BufferBinding {
330 storage: matrix.storage(),
331 access: *access,
332 }
333 })
334 .collect::<Vec<_>>()
335 })
336 .collect::<Vec<_>>();
337 let dispatches = stages
338 .iter()
339 .zip(&binding_sets)
340 .map(|(stage, bindings)| ComputeDispatch {
341 kernel: stage.kernel,
342 buffers: bindings,
343 push_constants: &stage.push_constants,
344 workgroups: stage.workgroups,
345 indirect: None,
346 })
347 .collect::<Vec<_>>();
348 let inputs = [parameter, gradient, momentum];
349 let outputs = [parameter, momentum];
350 parameter.runtime().record_split_semantic(
351 &dispatches,
352 SemanticDispatch {
353 contract: crate::core::operation::ml::MUON,
354 inputs: &inputs,
355 outputs: &outputs,
356 attributes,
357 },
358 )
359}
360
361fn allocate_muon_temp(
362 parameter: &Matrix,
363 shape: &[u32],
364 temporaries: &mut Vec<Matrix>,
365) -> Result<MuonSlot> {
366 let shape = shape
367 .iter()
368 .map(|value| *value as usize)
369 .collect::<Vec<_>>();
370 let count = shape.iter().try_fold(1_usize, |count, extent| {
371 count
372 .checked_mul(*extent)
373 .ok_or_else(|| Error::invalid_argument("ml.muon temporary size overflows usize"))
374 })?;
375 temporaries.push(Matrix::allocate(
376 parameter.runtime(),
377 shape,
378 count,
379 DType::F32,
380 )?);
381 Ok(MuonSlot::Temporary(temporaries.len() - 1))
382}
383
384fn muon_attributes(scalars: MuonScalars) -> Vec<OpAttribute> {
385 vec![
386 OpAttribute::Float {
387 name: "learning_rate".into(),
388 value: f64::from(scalars.learning_rate),
389 },
390 OpAttribute::Float {
391 name: "beta".into(),
392 value: f64::from(scalars.beta),
393 },
394 OpAttribute::Float {
395 name: "weight_decay".into(),
396 value: f64::from(scalars.weight_decay),
397 },
398 OpAttribute::Float {
399 name: "epsilon".into(),
400 value: f64::from(scalars.epsilon),
401 },
402 OpAttribute::UnsignedInteger {
403 name: "ns5_iterations".into(),
404 value: u64::from(scalars.ns5_iterations),
405 },
406 ]
407}
408
409fn muon_transpose_stage(input: MuonSlot, output: MuonSlot, rows: u32, columns: u32) -> MuonStage {
410 let count = rows * columns;
411 MuonStage {
412 kernel: KernelId::MlMuonTransposeF32,
413 bindings: vec![(input, BufferAccess::Read), (output, BufferAccess::Write)],
414 push_constants: vec![PushConstant::U32(rows), PushConstant::U32(columns)],
415 workgroups: KernelId::MlMuonTransposeF32.linear_workgroups(count),
416 }
417}
418
419fn muon_matmul_nt_stage(
420 runtime: &RuntimeHandle,
421 left: MuonSlot,
422 right: MuonSlot,
423 output: MuonSlot,
424 m: u32,
425 n: u32,
426 k: u32,
427) -> Result<MuonStage> {
428 let plan = crate::runtime::plan_matmul_nt(runtime, m, n, k)?;
429 let launch = crate::runtime::lower_matmul_nt(&plan, m, n, k)?;
430 let problem_slots = [left, right, output];
431 let mut bindings = Vec::with_capacity(launch.buffer_count);
432 for slot in 0..launch.buffer_count {
433 let index = usize::from(launch.buffer_order[slot]);
434 let problem_slot = problem_slots.get(index).copied().ok_or_else(|| {
435 Error::invalid_argument(format!(
436 "matmul launch slot {slot} binds missing problem buffer {index}"
437 ))
438 })?;
439 bindings.push((problem_slot, launch.buffer_accesses[slot]));
440 }
441 Ok(MuonStage {
442 kernel: launch.kernel_id,
443 bindings,
444 push_constants: launch.push_constants[..launch.push_count].to_vec(),
445 workgroups: launch.grid,
446 })
447}
448
449#[allow(clippy::too_many_arguments)]
450fn muon_matmul_axpby_stage(
451 a: MuonSlot,
452 b: MuonSlot,
453 residual: MuonSlot,
454 output: MuonSlot,
455 m: u32,
456 n: u32,
457 k: u32,
458 alpha: f32,
459 beta: f32,
460) -> MuonStage {
461 MuonStage {
462 kernel: KernelId::MlMuonMatmulAxpbyF32,
463 bindings: vec![
464 (a, BufferAccess::Read),
465 (b, BufferAccess::Read),
466 (residual, BufferAccess::Read),
467 (output, BufferAccess::Write),
468 ],
469 push_constants: vec![
470 PushConstant::U32(m),
471 PushConstant::U32(n),
472 PushConstant::U32(k),
473 PushConstant::F32(alpha),
474 PushConstant::F32(beta),
475 ],
476 workgroups: KernelId::MlMuonMatmulAxpbyF32.output_workgroups(m, n),
477 }
478}
479
480fn muon_linear_stage(
481 a: MuonSlot,
482 b: MuonSlot,
483 output: MuonSlot,
484 count: u32,
485 scale_a: f32,
486 scale_b: f32,
487) -> MuonStage {
488 MuonStage {
489 kernel: KernelId::MlMuonLinearCombinationF32,
490 bindings: vec![
491 (a, BufferAccess::Read),
492 (b, BufferAccess::Read),
493 (output, BufferAccess::Write),
494 ],
495 push_constants: vec![
496 PushConstant::U32(count),
497 PushConstant::F32(scale_a),
498 PushConstant::F32(scale_b),
499 ],
500 workgroups: KernelId::MlMuonLinearCombinationF32.linear_workgroups(count),
501 }
502}
503
504pub struct Muon {
509 pub(super) parameters: Vec<MuonParameterState>,
510 pub(super) learning_rate: f32,
511 pub(super) beta: f32,
512 pub(super) weight_decay: f32,
513 pub(super) epsilon: f32,
514 pub(super) ns5_iterations: u32,
515 pub(super) step: u64,
516}
517
518impl Muon {
519 pub fn new(parameters: impl IntoIterator<Item = Parameter>, learning_rate: f32) -> Result<Self> {
526 Self::new_with_hyperparameters(parameters, learning_rate, 0.95, 0.1, 1.0e-7, 5)
527 }
528
529 pub fn new_with_hyperparameters(
538 parameters: impl IntoIterator<Item = Parameter>,
539 learning_rate: f32,
540 beta: f32,
541 weight_decay: f32,
542 epsilon: f32,
543 ns5_iterations: u32,
544 ) -> Result<Self> {
545 if !learning_rate.is_finite() || learning_rate < 0.0 {
546 return Err(Error::invalid_argument(
547 "Muon learning rate must be finite and non-negative",
548 ));
549 }
550 if !beta.is_finite() || !(0.0..1.0).contains(&beta) {
551 return Err(Error::invalid_argument("Muon beta must be in [0, 1)"));
552 }
553 if !weight_decay.is_finite() || weight_decay < 0.0 {
554 return Err(Error::invalid_argument(
555 "Muon weight decay must be finite and non-negative",
556 ));
557 }
558 if !epsilon.is_finite() || epsilon <= 0.0 {
559 return Err(Error::invalid_argument(
560 "Muon epsilon must be finite and positive",
561 ));
562 }
563 let parameters = parameters.into_iter().collect::<Vec<_>>();
564 if parameters.is_empty() {
565 return Err(Error::invalid_argument(
566 "Muon requires at least one parameter",
567 ));
568 }
569 for (index, parameter) in parameters.iter().enumerate() {
570 if parameter.data().dtype() != DType::F32 {
571 return Err(Error::invalid_argument("Muon requires FP32 parameters"));
572 }
573 if parameters[..index]
574 .iter()
575 .any(|existing| existing.same_as(parameter))
576 {
577 return Err(Error::invalid_argument(
578 "Muon parameter handle appears more than once",
579 ));
580 }
581 }
582 let runtime = parameters[0].data().runtime().clone();
583 if parameters
584 .iter()
585 .any(|parameter| !runtime.same_as(parameter.data().runtime()))
586 {
587 return Err(Error::invalid_argument(
588 "Muon parameters must belong to one runtime",
589 ));
590 }
591 let mut states = Vec::with_capacity(parameters.len());
592 for parameter in parameters {
593 let data = parameter.data();
594 let momentum = Matrix::allocate(
595 data.runtime(),
596 data.shape().to_vec(),
597 data.num_elements(),
598 DType::F32,
599 )?;
600 states.push(MuonParameterState {
601 parameter,
602 momentum,
603 });
604 }
605 Ok(Self {
606 parameters: states,
607 learning_rate,
608 beta,
609 weight_decay,
610 epsilon,
611 ns5_iterations,
612 step: 0,
613 })
614 }
615
616 pub fn zero_grad(&self) {
618 for state in &self.parameters {
619 state.parameter.clear_gradient();
620 }
621 }
622
623 pub fn step(&mut self) -> Result<()> {
630 let next_step = self
631 .step
632 .checked_add(1)
633 .ok_or_else(|| Error::resource_exhausted("Muon step counter exhausted"))?;
634 let scalars = MuonScalars {
635 learning_rate: self.learning_rate,
636 beta: self.beta,
637 weight_decay: self.weight_decay,
638 epsilon: self.epsilon,
639 ns5_iterations: self.ns5_iterations,
640 };
641 let updates = self
642 .parameters
643 .iter()
644 .filter_map(|state| {
645 state
646 .parameter
647 .gradient()
648 .map(|gradient| (state, state.parameter.data(), gradient))
649 })
650 .collect::<Vec<_>>();
651 for (state, _, _) in &updates {
652 state.parameter.validate_can_update()?;
653 }
654 for (state, parameter, gradient) in &updates {
655 muon(parameter, gradient, &state.momentum, scalars)?;
656 }
657 for (state, _, _) in &updates {
658 state.parameter.mark_updated()?;
659 }
660 self.step = next_step;
661 Ok(())
662 }
663
664 pub const fn learning_rate(&self) -> f32 {
666 self.learning_rate
667 }
668
669 pub fn set_learning_rate(&mut self, learning_rate: f32) -> Result<()> {
675 if !learning_rate.is_finite() || learning_rate < 0.0 {
676 return Err(Error::invalid_argument(
677 "Muon learning rate must be finite and non-negative",
678 ));
679 }
680 self.learning_rate = learning_rate;
681 Ok(())
682 }
683
684 pub const fn step_count(&self) -> u64 {
686 self.step
687 }
688
689 pub(super) fn belongs_to_runtime(&self, runtime: &Runtime) -> bool {
690 runtime.same_as_handle(self.parameters[0].parameter.data().runtime())
691 }
692
693 pub(super) fn checkpoint(&self) -> Result<OptimizerCheckpoint> {
694 Ok(OptimizerCheckpoint {
695 kind: "Muon",
696 step: self.step,
697 applied_step: None,
698 learning_rate: self.learning_rate,
699 beta1: self.beta,
700 beta2: 0.0,
701 epsilon: self.epsilon,
702 weight_decay: self.weight_decay,
703 parameters: self
704 .parameters
705 .iter()
706 .map(|state| state.parameter.clone())
707 .collect(),
708 first_state: self
709 .parameters
710 .iter()
711 .map(|state| state.momentum.clone())
712 .collect(),
713 second_state: Vec::new(),
714 })
715 }
716
717 pub(super) fn validate_checkpoint(&self, state: &OptimizerRestore) -> Result<()> {
718 if state.kind != "Muon"
719 || state.first_state.len() != self.parameters.len()
720 || !state.second_state.is_empty()
721 || !state.learning_rate.is_finite()
722 || state.learning_rate < 0.0
723 || !state.beta1.is_finite()
724 || !(0.0..1.0).contains(&state.beta1)
725 || state.beta2 != 0.0
726 || !state.epsilon.is_finite()
727 || state.epsilon <= 0.0
728 || !state.weight_decay.is_finite()
729 || state.weight_decay < 0.0
730 {
731 return Err(Error::invalid_argument("invalid Muon checkpoint state"));
732 }
733 for (parameter_state, momentum) in self.parameters.iter().zip(&state.first_state) {
734 let data = parameter_state.parameter.data();
735 if momentum.shape() != data.shape()
736 || momentum.dtype() != DType::F32
737 || !momentum.runtime().same_as(data.runtime())
738 {
739 return Err(Error::invalid_argument(
740 "Muon checkpoint momentum contract mismatch",
741 ));
742 }
743 }
744 Ok(())
745 }
746
747 pub(super) fn restore_checkpoint(&mut self, state: OptimizerRestore) -> Result<()> {
748 self.validate_checkpoint(&state)?;
749 for (parameter_state, momentum) in self.parameters.iter_mut().zip(state.first_state) {
750 parameter_state.momentum = momentum;
751 }
752 self.step = state.step;
753 self.learning_rate = state.learning_rate;
754 self.beta = state.beta1;
755 self.epsilon = state.epsilon;
756 self.weight_decay = state.weight_decay;
757 Ok(())
758 }
759}
760
761impl Optimizer for Muon {
762 fn zero_grad(&self) {
763 Self::zero_grad(self);
764 }
765
766 fn step(&mut self) -> Result<()> {
767 Self::step(self)
768 }
769
770 fn learning_rate(&self) -> f32 {
771 Self::learning_rate(self)
772 }
773
774 fn set_learning_rate(&mut self, learning_rate: f32) -> Result<()> {
775 Self::set_learning_rate(self, learning_rate)
776 }
777
778 fn step_count(&self) -> u64 {
779 Self::step_count(self)
780 }
781
782 fn belongs_to(&self, runtime: &Runtime) -> bool {
783 self.belongs_to_runtime(runtime)
784 }
785}
786
787impl checkpoint_capability::Persistence for Muon {
788 fn checkpoint_state(&self) -> Result<OptimizerCheckpoint> {
789 Self::checkpoint(self)
790 }
791
792 fn validate_checkpoint_state(&self, state: &OptimizerRestore) -> Result<()> {
793 Self::validate_checkpoint(self, state)
794 }
795
796 fn restore_checkpoint_state(&mut self, state: OptimizerRestore) -> Result<()> {
797 Self::restore_checkpoint(self, state)
798 }
799}