1use crate::ml::Parameter;
4use crate::ml::validation::{shader_u32, validate_f32_same_runtime};
5use crate::runtime::{BufferBinding, ComputeDispatch, KernelId, PushConstant, SemanticDispatch};
6use crate::{DType, Error, Matrix, OpAttribute, Result, Runtime};
7
8use super::optimizer::{
9 MomentParameterState, Optimizer, OptimizerCheckpoint, OptimizerRestore, checkpoint_capability,
10 next_optimizer_id,
11};
12
13#[derive(Clone, Copy)]
14pub(super) struct AdamWScalars {
15 pub(super) step: u32,
16 pub(super) learning_rate: f32,
17 pub(super) beta1: f32,
18 pub(super) beta2: f32,
19 pub(super) epsilon: f32,
20 pub(super) weight_decay: f32,
21}
22
23#[derive(Clone, Copy)]
24pub(super) struct AdamWBatchEntry<'a> {
25 pub(super) parameter: &'a Matrix,
26 pub(super) gradient: &'a Matrix,
27 pub(super) first_moment: &'a Matrix,
28 pub(super) second_moment: &'a Matrix,
29}
30
31fn adamw_graph_advance(state: &Matrix) -> Result<()> {
32 const OPERATION: &str = crate::core::operation::ml::ADAMW_GRAPH_ADVANCE.name();
33 if state.dtype() != DType::U32 || state.shape() != [6] {
34 return Err(Error::invalid_argument(format!(
35 "{OPERATION} requires U32 optimizer state [6]"
36 )));
37 }
38 let buffers = [BufferBinding::read_write(state.storage())];
39 {
40 let inputs: &[&Matrix] = &[state];
41 let outputs: &[&Matrix] = &[state];
42 let attributes: &[OpAttribute] = &[];
43 let dispatch = ComputeDispatch {
44 kernel: KernelId::MlAdamWGraphAdvanceU32,
45 buffers: &buffers,
46 push_constants: &[],
47 workgroups: [1, 1, 1],
48 indirect: None,
49 };
50 let contract = dispatch.kernel.semantic_contract().ok_or_else(|| {
51 Error::internal(format!(
52 "lowering-only kernel {} cannot own one semantic ML operation",
53 dispatch.kernel.report_name()
54 ))
55 })?;
56 let runtime = inputs
57 .first()
58 .ok_or_else(|| Error::internal("semantic ML dispatch requires an input"))?
59 .runtime();
60 runtime.record_semantic(
61 dispatch,
62 SemanticDispatch {
63 contract,
64 inputs,
65 outputs,
66 attributes,
67 },
68 )
69 }
70}
71
72fn adamw_gated_graph_advance(state: &Matrix, flag: &Matrix) -> Result<()> {
73 const OPERATION: &str = crate::core::operation::ml::ADAMW_GATED_GRAPH_ADVANCE.name();
74 if state.dtype() != DType::U32 || state.shape() != [6] {
75 return Err(Error::invalid_argument(format!(
76 "{OPERATION} requires U32 optimizer state [6]"
77 )));
78 }
79 if flag.dtype() != DType::F32
80 || flag.num_elements() != 1
81 || !flag.runtime().same_as(state.runtime())
82 {
83 return Err(Error::invalid_argument(format!(
84 "{OPERATION} requires a same-runtime single-element F32 finite flag"
85 )));
86 }
87 let buffers = [
88 BufferBinding::read_write(state.storage()),
89 BufferBinding::read(flag.storage()),
90 ];
91 {
92 let inputs: &[&Matrix] = &[state, flag];
93 let outputs: &[&Matrix] = &[state];
94 let attributes: &[OpAttribute] = &[];
95 let dispatch = ComputeDispatch {
96 kernel: KernelId::MlAdamWGatedGraphAdvanceU32,
97 buffers: &buffers,
98 push_constants: &[],
99 workgroups: [1, 1, 1],
100 indirect: None,
101 };
102 let contract = dispatch.kernel.semantic_contract().ok_or_else(|| {
103 Error::internal(format!(
104 "lowering-only kernel {} cannot own one semantic ML operation",
105 dispatch.kernel.report_name()
106 ))
107 })?;
108 let runtime = inputs
109 .first()
110 .ok_or_else(|| Error::internal("semantic ML dispatch requires an input"))?
111 .runtime();
112 runtime.record_semantic(
113 dispatch,
114 SemanticDispatch {
115 contract,
116 inputs,
117 outputs,
118 attributes,
119 },
120 )
121 }
122}
123
124fn adamw_gated_graph(
125 parameter: &Matrix,
126 gradient: &Matrix,
127 first_moment: &Matrix,
128 second_moment: &Matrix,
129 state: &Matrix,
130 flag: &Matrix,
131) -> Result<()> {
132 const OPERATION: &str = crate::core::operation::ml::ADAMW_GATED_GRAPH.name();
133 validate_f32_same_runtime(
134 OPERATION,
135 &[parameter, gradient, first_moment, second_moment, flag],
136 )?;
137 if state.dtype() != DType::U32 || !state.runtime().same_as(parameter.runtime()) {
138 return Err(Error::invalid_argument(format!(
139 "{OPERATION} requires same-runtime U32 optimizer state"
140 )));
141 }
142 if flag.num_elements() != 1 {
143 return Err(Error::invalid_argument(format!(
144 "{OPERATION} requires a single-element F32 finite flag"
145 )));
146 }
147 for candidate in [gradient, first_moment, second_moment] {
148 if candidate.shape() != parameter.shape() {
149 return Err(Error::invalid_argument(format!(
150 "{OPERATION} requires identical parameter, gradient, and moment shapes"
151 )));
152 }
153 }
154 if state.shape() != [6] {
155 return Err(Error::invalid_argument(format!(
156 "{OPERATION} requires optimizer state [6]"
157 )));
158 }
159 let element_count = shader_u32(parameter.num_elements(), "element count", OPERATION)?;
160 if element_count == 0 {
161 return Ok(());
162 }
163 let buffers = [
164 BufferBinding::read_write(parameter.storage()),
165 BufferBinding::read(gradient.storage()),
166 BufferBinding::read_write(first_moment.storage()),
167 BufferBinding::read_write(second_moment.storage()),
168 BufferBinding::read(state.storage()),
169 BufferBinding::read(flag.storage()),
170 ];
171 let push_constants = [PushConstant::U32(element_count)];
172 {
173 let inputs: &[&Matrix] = &[
174 parameter,
175 gradient,
176 first_moment,
177 second_moment,
178 state,
179 flag,
180 ];
181 let outputs: &[&Matrix] = &[parameter, first_moment, second_moment];
182 let attributes: &[OpAttribute] = &[];
183 let dispatch = ComputeDispatch {
184 kernel: KernelId::MlAdamWGatedGraphF32,
185 buffers: &buffers,
186 push_constants: &push_constants,
187 workgroups: KernelId::MlAdamWGatedGraphF32.linear_workgroups(element_count),
188 indirect: None,
189 };
190 let contract = dispatch.kernel.semantic_contract().ok_or_else(|| {
191 Error::internal(format!(
192 "lowering-only kernel {} cannot own one semantic ML operation",
193 dispatch.kernel.report_name()
194 ))
195 })?;
196 let runtime = inputs
197 .first()
198 .ok_or_else(|| Error::internal("semantic ML dispatch requires an input"))?
199 .runtime();
200 runtime.record_semantic(
201 dispatch,
202 SemanticDispatch {
203 contract,
204 inputs,
205 outputs,
206 attributes,
207 },
208 )
209 }
210}
211
212fn adamw_graph(
213 parameter: &Matrix,
214 gradient: &Matrix,
215 first_moment: &Matrix,
216 second_moment: &Matrix,
217 state: &Matrix,
218) -> Result<()> {
219 const OPERATION: &str = crate::core::operation::ml::ADAMW_GRAPH.name();
220 validate_f32_same_runtime(
221 OPERATION,
222 &[parameter, gradient, first_moment, second_moment],
223 )?;
224 if state.dtype() != DType::U32 || !state.runtime().same_as(parameter.runtime()) {
225 return Err(Error::invalid_argument(format!(
226 "{OPERATION} requires same-runtime U32 optimizer state"
227 )));
228 }
229 for candidate in [gradient, first_moment, second_moment] {
230 if candidate.shape() != parameter.shape() {
231 return Err(Error::invalid_argument(format!(
232 "{OPERATION} requires identical parameter, gradient, and moment shapes"
233 )));
234 }
235 }
236 if state.shape() != [6] {
237 return Err(Error::invalid_argument(format!(
238 "{OPERATION} requires optimizer state [6]"
239 )));
240 }
241 let element_count = shader_u32(parameter.num_elements(), "element count", OPERATION)?;
242 if element_count == 0 {
243 return Ok(());
244 }
245 let buffers = [
246 BufferBinding::read_write(parameter.storage()),
247 BufferBinding::read(gradient.storage()),
248 BufferBinding::read_write(first_moment.storage()),
249 BufferBinding::read_write(second_moment.storage()),
250 BufferBinding::read(state.storage()),
251 ];
252 let push_constants = [PushConstant::U32(element_count)];
253 let kernel = KernelId::MlAdamWGraphF32;
254 {
255 let inputs: &[&Matrix] = &[parameter, gradient, first_moment, second_moment, state];
256 let outputs: &[&Matrix] = &[parameter, first_moment, second_moment];
257 let attributes: &[OpAttribute] = &[];
258 let dispatch = ComputeDispatch {
259 kernel,
260 buffers: &buffers,
261 push_constants: &push_constants,
262 workgroups: kernel.linear_workgroups(element_count),
263 indirect: None,
264 };
265 let contract = dispatch.kernel.semantic_contract().ok_or_else(|| {
266 Error::internal(format!(
267 "lowering-only kernel {} cannot own one semantic ML operation",
268 dispatch.kernel.report_name()
269 ))
270 })?;
271 let runtime = inputs
272 .first()
273 .ok_or_else(|| Error::internal("semantic ML dispatch requires an input"))?
274 .runtime();
275 runtime.record_semantic(
276 dispatch,
277 SemanticDispatch {
278 contract,
279 inputs,
280 outputs,
281 attributes,
282 },
283 )
284 }
285}
286
287fn adamw_many4_graph(entries: &[AdamWBatchEntry<'_>; 4], state: &Matrix) -> Result<()> {
288 const OPERATION: &str = "ml.adamw_many4_graph";
289 let counts = validate_adamw_batch(entries, Some(state), OPERATION)?;
290 let maximum = counts.iter().copied().max().unwrap_or(0);
291 if maximum == 0 {
292 return Ok(());
293 }
294 let buffers = adamw_many4_graph_buffers(entries, state);
295 let push_constants = counts.map(PushConstant::U32);
296 let input0 = adamw_graph_inputs(entries[0], state);
297 let input1 = adamw_graph_inputs(entries[1], state);
298 let input2 = adamw_graph_inputs(entries[2], state);
299 let input3 = adamw_graph_inputs(entries[3], state);
300 let output0 = adamw_outputs(entries[0]);
301 let output1 = adamw_outputs(entries[1]);
302 let output2 = adamw_outputs(entries[2]);
303 let output3 = adamw_outputs(entries[3]);
304 let contract = crate::core::operation::ml::ADAMW_GRAPH;
305 let semantics = [
306 SemanticDispatch {
307 contract,
308 inputs: &input0,
309 outputs: &output0,
310 attributes: &[],
311 },
312 SemanticDispatch {
313 contract,
314 inputs: &input1,
315 outputs: &output1,
316 attributes: &[],
317 },
318 SemanticDispatch {
319 contract,
320 inputs: &input2,
321 outputs: &output2,
322 attributes: &[],
323 },
324 SemanticDispatch {
325 contract,
326 inputs: &input3,
327 outputs: &output3,
328 attributes: &[],
329 },
330 ];
331 let kernel = KernelId::MlAdamWMany4GraphF32;
332 entries[0].parameter.runtime().record_fused_semantic(
333 ComputeDispatch {
334 kernel,
335 buffers: &buffers,
336 push_constants: &push_constants,
337 workgroups: kernel.linear_workgroups(maximum),
338 indirect: None,
339 },
340 &semantics,
341 )
342}
343
344fn adamw(
345 parameter: &Matrix,
346 gradient: &Matrix,
347 first_moment: &Matrix,
348 second_moment: &Matrix,
349 scalars: AdamWScalars,
350) -> Result<()> {
351 const OPERATION: &str = crate::core::operation::ml::ADAMW.name();
352 validate_f32_same_runtime(
353 OPERATION,
354 &[parameter, gradient, first_moment, second_moment],
355 )?;
356 for candidate in [gradient, first_moment, second_moment] {
357 if candidate.shape() != parameter.shape() {
358 return Err(Error::invalid_argument(format!(
359 "{OPERATION} requires identical parameter, gradient, and moment shapes"
360 )));
361 }
362 }
363 let element_count = shader_u32(parameter.num_elements(), "element count", OPERATION)?;
364 if element_count != 0 {
365 let buffers = [
366 BufferBinding::read_write(parameter.storage()),
367 BufferBinding::read(gradient.storage()),
368 BufferBinding::read_write(first_moment.storage()),
369 BufferBinding::read_write(second_moment.storage()),
370 ];
371 let push_constants = [
372 PushConstant::U32(element_count),
373 PushConstant::U32(scalars.step),
374 PushConstant::F32(scalars.learning_rate),
375 PushConstant::F32(scalars.beta1),
376 PushConstant::F32(scalars.beta2),
377 PushConstant::F32(scalars.epsilon),
378 PushConstant::F32(scalars.weight_decay),
379 ];
380 let kernel = KernelId::MlAdamWF32;
381 let attributes = adamw_attributes(scalars);
382 {
383 let inputs: &[&Matrix] = &[parameter, gradient, first_moment, second_moment];
384 let outputs: &[&Matrix] = &[parameter, first_moment, second_moment];
385 let attributes: &[OpAttribute] = &attributes;
386 let dispatch = ComputeDispatch {
387 kernel,
388 buffers: &buffers,
389 push_constants: &push_constants,
390 workgroups: kernel.linear_workgroups(element_count),
391 indirect: None,
392 };
393 let contract = dispatch.kernel.semantic_contract().ok_or_else(|| {
394 Error::internal(format!(
395 "lowering-only kernel {} cannot own one semantic ML operation",
396 dispatch.kernel.report_name()
397 ))
398 })?;
399 let runtime = inputs
400 .first()
401 .ok_or_else(|| Error::internal("semantic ML dispatch requires an input"))?
402 .runtime();
403 runtime.record_semantic(
404 dispatch,
405 SemanticDispatch {
406 contract,
407 inputs,
408 outputs,
409 attributes,
410 },
411 )
412 }?;
413 }
414 Ok(())
415}
416
417fn adamw_many4(entries: &[AdamWBatchEntry<'_>; 4], scalars: AdamWScalars) -> Result<()> {
418 const OPERATION: &str = "ml.adamw_many4";
419 let counts = validate_adamw_batch(entries, None, OPERATION)?;
420 let maximum = counts.iter().copied().max().unwrap_or(0);
421 if maximum == 0 {
422 return Ok(());
423 }
424 let buffers = adamw_many4_buffers(entries);
425 let push_constants = [
426 PushConstant::U32(counts[0]),
427 PushConstant::U32(counts[1]),
428 PushConstant::U32(counts[2]),
429 PushConstant::U32(counts[3]),
430 PushConstant::F32(scalars.learning_rate),
431 PushConstant::F32(scalars.beta1),
432 PushConstant::F32(scalars.beta2),
433 PushConstant::F32(scalars.epsilon),
434 PushConstant::F32(scalars.weight_decay),
435 PushConstant::U32(scalars.step),
436 ];
437 let attributes = adamw_attributes(scalars);
438 let input0 = adamw_inputs(entries[0]);
439 let input1 = adamw_inputs(entries[1]);
440 let input2 = adamw_inputs(entries[2]);
441 let input3 = adamw_inputs(entries[3]);
442 let output0 = adamw_outputs(entries[0]);
443 let output1 = adamw_outputs(entries[1]);
444 let output2 = adamw_outputs(entries[2]);
445 let output3 = adamw_outputs(entries[3]);
446 let contract = crate::core::operation::ml::ADAMW;
447 let semantics = [
448 SemanticDispatch {
449 contract,
450 inputs: &input0,
451 outputs: &output0,
452 attributes: &attributes,
453 },
454 SemanticDispatch {
455 contract,
456 inputs: &input1,
457 outputs: &output1,
458 attributes: &attributes,
459 },
460 SemanticDispatch {
461 contract,
462 inputs: &input2,
463 outputs: &output2,
464 attributes: &attributes,
465 },
466 SemanticDispatch {
467 contract,
468 inputs: &input3,
469 outputs: &output3,
470 attributes: &attributes,
471 },
472 ];
473 let kernel = KernelId::MlAdamWMany4F32;
474 entries[0].parameter.runtime().record_fused_semantic(
475 ComputeDispatch {
476 kernel,
477 buffers: &buffers,
478 push_constants: &push_constants,
479 workgroups: kernel.linear_workgroups(maximum),
480 indirect: None,
481 },
482 &semantics,
483 )
484}
485
486fn validate_adamw_batch(
487 entries: &[AdamWBatchEntry<'_>; 4],
488 state: Option<&Matrix>,
489 operation: &'static str,
490) -> Result<[u32; 4]> {
491 let runtime = entries[0].parameter.runtime();
492 if let Some(state) = state
493 && (state.dtype() != DType::U32 || state.shape() != [6] || !runtime.same_as(state.runtime()))
494 {
495 return Err(Error::invalid_argument(format!(
496 "{operation} requires same-runtime U32 optimizer state [6]"
497 )));
498 }
499 let mut counts = [0_u32; 4];
500 for (index, entry) in entries.iter().enumerate() {
501 validate_f32_same_runtime(
502 operation,
503 &[
504 entry.parameter,
505 entry.gradient,
506 entry.first_moment,
507 entry.second_moment,
508 ],
509 )?;
510 if !runtime.same_as(entry.parameter.runtime())
511 || [entry.gradient, entry.first_moment, entry.second_moment]
512 .iter()
513 .any(|candidate| candidate.shape() != entry.parameter.shape())
514 {
515 return Err(Error::invalid_argument(format!(
516 "{operation} requires four same-runtime parameter, gradient, and moment groups with identical per-group shapes"
517 )));
518 }
519 counts[index] = shader_u32(entry.parameter.num_elements(), "element count", operation)?;
520 }
521 Ok(counts)
522}
523
524fn adamw_inputs(entry: AdamWBatchEntry<'_>) -> [&Matrix; 4] {
525 [
526 entry.parameter,
527 entry.gradient,
528 entry.first_moment,
529 entry.second_moment,
530 ]
531}
532
533fn adamw_graph_inputs<'a>(entry: AdamWBatchEntry<'a>, state: &'a Matrix) -> [&'a Matrix; 5] {
534 [
535 entry.parameter,
536 entry.gradient,
537 entry.first_moment,
538 entry.second_moment,
539 state,
540 ]
541}
542
543fn adamw_outputs(entry: AdamWBatchEntry<'_>) -> [&Matrix; 3] {
544 [entry.parameter, entry.first_moment, entry.second_moment]
545}
546
547fn adamw_many4_buffers<'a>(entries: &[AdamWBatchEntry<'a>; 4]) -> [BufferBinding<'a>; 16] {
548 [
549 BufferBinding::read_write(entries[0].parameter.storage()),
550 BufferBinding::read(entries[0].gradient.storage()),
551 BufferBinding::read_write(entries[0].first_moment.storage()),
552 BufferBinding::read_write(entries[0].second_moment.storage()),
553 BufferBinding::read_write(entries[1].parameter.storage()),
554 BufferBinding::read(entries[1].gradient.storage()),
555 BufferBinding::read_write(entries[1].first_moment.storage()),
556 BufferBinding::read_write(entries[1].second_moment.storage()),
557 BufferBinding::read_write(entries[2].parameter.storage()),
558 BufferBinding::read(entries[2].gradient.storage()),
559 BufferBinding::read_write(entries[2].first_moment.storage()),
560 BufferBinding::read_write(entries[2].second_moment.storage()),
561 BufferBinding::read_write(entries[3].parameter.storage()),
562 BufferBinding::read(entries[3].gradient.storage()),
563 BufferBinding::read_write(entries[3].first_moment.storage()),
564 BufferBinding::read_write(entries[3].second_moment.storage()),
565 ]
566}
567
568fn adamw_many4_graph_buffers<'a>(
569 entries: &[AdamWBatchEntry<'a>; 4],
570 state: &'a Matrix,
571) -> [BufferBinding<'a>; 17] {
572 let base = adamw_many4_buffers(entries);
573 [
574 base[0],
575 base[1],
576 base[2],
577 base[3],
578 base[4],
579 base[5],
580 base[6],
581 base[7],
582 base[8],
583 base[9],
584 base[10],
585 base[11],
586 base[12],
587 base[13],
588 base[14],
589 base[15],
590 BufferBinding::read(state.storage()),
591 ]
592}
593
594fn adamw_attributes(scalars: AdamWScalars) -> [OpAttribute; 6] {
595 [
596 OpAttribute::UnsignedInteger {
597 name: "step".into(),
598 value: u64::from(scalars.step),
599 },
600 OpAttribute::Float {
601 name: "learning_rate".into(),
602 value: f64::from(scalars.learning_rate),
603 },
604 OpAttribute::Float {
605 name: "beta1".into(),
606 value: f64::from(scalars.beta1),
607 },
608 OpAttribute::Float {
609 name: "beta2".into(),
610 value: f64::from(scalars.beta2),
611 },
612 OpAttribute::Float {
613 name: "epsilon".into(),
614 value: f64::from(scalars.epsilon),
615 },
616 OpAttribute::Float {
617 name: "weight_decay".into(),
618 value: f64::from(scalars.weight_decay),
619 },
620 ]
621}
622
623pub struct AdamWProgramSignature {
624 pub(crate) optimizer_id: u64,
625 pub(crate) state_id: u64,
626 pub(crate) parameter_ids: Vec<u64>,
627 pub(crate) gradient_ids: Vec<u64>,
628 pub(crate) moment_ids: Vec<(u64, u64)>,
629 pub(crate) gate_id: Option<u64>,
630 pub(crate) base_step: u32,
631}
632
633pub struct AdamW {
635 pub(super) id: u64,
636 pub(super) parameters: Vec<MomentParameterState>,
637 pub(super) learning_rate: f32,
638 pub(super) beta1: f32,
639 pub(super) beta2: f32,
640 pub(super) epsilon: f32,
641 pub(super) weight_decay: f32,
642 pub(super) step: u32,
643 applied_step: Option<u32>,
644 pub(super) graph_state: Option<Matrix>,
645 pub(super) gate: Option<Matrix>,
646 pub(super) param_group: Vec<usize>,
649 pub(super) groups: Vec<AdamWGroupMeta>,
650}
651
652pub(super) struct AdamWGroupMeta {
654 pub(super) lr_scale: f32,
655 pub(super) weight_decay: Option<f32>,
656 pub(super) frozen: bool,
657}
658
659impl AdamW {
660 pub fn new(parameters: impl IntoIterator<Item = Parameter>, learning_rate: f32) -> Result<Self> {
668 Self::new_with_hyperparameters(parameters, learning_rate, 0.9, 0.999, 1.0e-8, 0.01)
669 }
670
671 pub fn new_with_hyperparameters(
678 parameters: impl IntoIterator<Item = Parameter>,
679 learning_rate: f32,
680 beta1: f32,
681 beta2: f32,
682 epsilon: f32,
683 weight_decay: f32,
684 ) -> Result<Self> {
685 if !learning_rate.is_finite() || learning_rate < 0.0 {
686 return Err(Error::invalid_argument(
687 "AdamW learning rate must be finite and non-negative",
688 ));
689 }
690 if !beta1.is_finite() || !(0.0..1.0).contains(&beta1) {
691 return Err(Error::invalid_argument("AdamW beta1 must be in [0, 1)"));
692 }
693 if !beta2.is_finite() || !(0.0..1.0).contains(&beta2) {
694 return Err(Error::invalid_argument("AdamW beta2 must be in [0, 1)"));
695 }
696 if !epsilon.is_finite() || epsilon <= 0.0 {
697 return Err(Error::invalid_argument(
698 "AdamW epsilon must be finite and positive",
699 ));
700 }
701 if !weight_decay.is_finite() || weight_decay < 0.0 {
702 return Err(Error::invalid_argument(
703 "AdamW weight decay must be finite and non-negative",
704 ));
705 }
706 let parameters = parameters.into_iter().collect::<Vec<_>>();
707 if parameters.is_empty() {
708 return Err(Error::invalid_argument(
709 "AdamW requires at least one parameter",
710 ));
711 }
712 for (index, parameter) in parameters.iter().enumerate() {
713 if parameters[..index]
714 .iter()
715 .any(|existing| existing.same_as(parameter))
716 {
717 return Err(Error::invalid_argument(
718 "AdamW parameter handle appears more than once",
719 ));
720 }
721 }
722 let runtime = parameters[0].data().runtime().clone();
723 if parameters
724 .iter()
725 .any(|parameter| !runtime.same_as(parameter.data().runtime()))
726 {
727 return Err(Error::invalid_argument(
728 "AdamW parameters must belong to one runtime",
729 ));
730 }
731 let mut states = Vec::with_capacity(parameters.len());
732 for parameter in parameters {
733 let data = parameter.data();
734 let first_moment = Matrix::allocate(
735 data.runtime(),
736 data.shape().to_vec(),
737 data.num_elements(),
738 DType::F32,
739 )?;
740 let second_moment = Matrix::allocate(
741 data.runtime(),
742 data.shape().to_vec(),
743 data.num_elements(),
744 DType::F32,
745 )?;
746 states.push(MomentParameterState {
747 parameter,
748 first_moment,
749 second_moment,
750 });
751 }
752 Ok(Self {
753 id: next_optimizer_id()?,
754 parameters: states,
755 learning_rate,
756 beta1,
757 beta2,
758 epsilon,
759 weight_decay,
760 step: 0,
761 applied_step: None,
762 graph_state: None,
763 gate: None,
764 param_group: Vec::new(),
765 groups: Vec::new(),
766 })
767 }
768
769 pub fn new_with_groups(
785 groups: Vec<crate::ml::optim::ParameterGroup>,
786 learning_rate: f32,
787 beta1: f32,
788 beta2: f32,
789 epsilon: f32,
790 weight_decay: f32,
791 ) -> Result<Self> {
792 if groups.is_empty() {
793 return Err(Error::invalid_argument(
794 "AdamW requires at least one parameter group",
795 ));
796 }
797 let mut parameters = Vec::new();
798 let mut param_group = Vec::new();
799 let mut metas = Vec::new();
800 for (group_index, group) in groups.into_iter().enumerate() {
801 if group.parameters.is_empty() {
802 return Err(Error::invalid_argument(format!(
803 "AdamW group '{}' must not be empty",
804 group.name
805 )));
806 }
807 if !group.lr_scale.is_finite() || group.lr_scale < 0.0 {
808 return Err(Error::invalid_argument(format!(
809 "AdamW group '{}' learning-rate scale must be finite and non-negative",
810 group.name
811 )));
812 }
813 if let Some(decay) = group.weight_decay
814 && (!decay.is_finite() || decay < 0.0)
815 {
816 return Err(Error::invalid_argument(format!(
817 "AdamW group '{}' weight decay must be finite and non-negative",
818 group.name
819 )));
820 }
821 for parameter in group.parameters {
822 parameters.push(parameter);
823 param_group.push(group_index);
824 }
825 metas.push(AdamWGroupMeta {
826 lr_scale: group.lr_scale,
827 weight_decay: group.weight_decay,
828 frozen: group.frozen,
829 });
830 }
831 let mut optimizer = Self::new_with_hyperparameters(
832 parameters,
833 learning_rate,
834 beta1,
835 beta2,
836 epsilon,
837 weight_decay,
838 )?;
839 optimizer.param_group = param_group;
840 optimizer.groups = metas;
841 Ok(optimizer)
842 }
843
844 pub(super) fn group_scalars(&self, step: u32, group: usize) -> AdamWScalars {
846 let meta = &self.groups[group];
847 AdamWScalars {
848 step,
849 learning_rate: self.learning_rate * meta.lr_scale,
850 beta1: self.beta1,
851 beta2: self.beta2,
852 epsilon: self.epsilon,
853 weight_decay: meta.weight_decay.unwrap_or(self.weight_decay),
854 }
855 }
856
857 pub(super) fn has_nonuniform_groups(&self) -> bool {
859 !self.groups.is_empty()
860 && self
861 .groups
862 .iter()
863 .any(|meta| meta.lr_scale != 1.0 || meta.weight_decay.is_some() || meta.frozen)
864 }
865
866 pub fn zero_grad(&self) {
868 for state in &self.parameters {
869 state.parameter.clear_gradient();
870 }
871 }
872
873 pub fn step(&mut self) -> Result<()> {
884 let capture_active = self.parameters[0]
885 .parameter
886 .data()
887 .runtime()
888 .capture_active();
889 if capture_active {
890 return self.record_captured_step(self.applied_step.unwrap_or(self.step));
891 }
892 let step = self
893 .step
894 .checked_add(1)
895 .ok_or_else(|| Error::resource_exhausted("AdamW step counter exhausted"))?;
896 let applied_step = self
897 .applied_step_at_boundary()?
898 .checked_add(1)
899 .ok_or_else(|| Error::resource_exhausted("AdamW applied step counter exhausted"))?;
900 let uniform_scalars = AdamWScalars {
901 step: applied_step,
902 learning_rate: self.learning_rate,
903 beta1: self.beta1,
904 beta2: self.beta2,
905 epsilon: self.epsilon,
906 weight_decay: self.weight_decay,
907 };
908 let updates = self
909 .parameters
910 .iter()
911 .enumerate()
912 .filter(|(index, _state)| {
913 !self
916 .param_group
917 .get(*index)
918 .is_some_and(|group| self.groups[*group].frozen)
919 })
920 .filter_map(|(index, state)| {
921 state
922 .parameter
923 .gradient()
924 .map(|gradient| (index, state, state.parameter.data(), gradient))
925 })
926 .collect::<Vec<_>>();
927 let mut span_start = 0;
931 while span_start < updates.len() {
932 let group = self.param_group.get(updates[span_start].0).copied();
933 let mut span_end = span_start + 1;
934 while span_end < updates.len() && self.param_group.get(updates[span_end].0).copied() == group
935 {
936 span_end += 1;
937 }
938 let scalars = match group {
939 Some(group) => self.group_scalars(applied_step, group),
940 None => uniform_scalars,
941 };
942 let span = &updates[span_start..span_end];
943 let mut batch_start = 0;
944 while batch_start + 4 <= span.len() {
945 let entries = std::array::from_fn(|index| {
946 let (_, state, parameter, gradient) = &span[batch_start + index];
947 AdamWBatchEntry {
948 parameter,
949 gradient,
950 first_moment: &state.first_moment,
951 second_moment: &state.second_moment,
952 }
953 });
954 adamw_many4(&entries, scalars)?;
955 batch_start += 4;
956 }
957 for (_, state, parameter, gradient) in &span[batch_start..] {
958 adamw(
959 parameter,
960 gradient,
961 &state.first_moment,
962 &state.second_moment,
963 scalars,
964 )?;
965 }
966 span_start = span_end;
967 }
968 for (_, state, _, _) in &updates {
969 state.parameter.mark_updated()?;
970 }
971 self.step = step;
972 self.applied_step = (applied_step != step).then_some(applied_step);
973 self.graph_state = None;
974 Ok(())
975 }
976
977 pub(crate) fn record_captured_step(&mut self, applied_step: u32) -> Result<()> {
978 if self.step == u32::MAX {
979 return Err(Error::resource_exhausted("AdamW step counter exhausted"));
980 }
981 if self.has_nonuniform_groups() {
982 return Err(Error::failed_precondition(
983 "captured AdamW steps do not yet admit non-uniform parameter groups: recorded programs bake uniform scalars — run grouped training eagerly",
984 ));
985 }
986 let gradients = self
987 .parameters
988 .iter()
989 .map(|state| {
990 state.parameter.gradient().ok_or_else(|| {
991 Error::failed_precondition(
992 "captured AdamW requires one stable gradient for every parameter",
993 )
994 })
995 })
996 .collect::<Result<Vec<_>>>()?;
997 let runtime = self.parameters[0].parameter.data().runtime().clone();
998 let state = Matrix::new_from_slice_handle(
999 &runtime,
1000 vec![6],
1001 &[
1002 applied_step,
1003 self.learning_rate.to_bits(),
1004 self.beta1.to_bits(),
1005 self.beta2.to_bits(),
1006 self.epsilon.to_bits(),
1007 self.weight_decay.to_bits(),
1008 ],
1009 )?;
1010 if let Some(flag) = &self.gate {
1011 adamw_gated_graph_advance(&state, flag)?;
1012 } else {
1013 adamw_graph_advance(&state)?;
1014 }
1015 let parameters = self
1016 .parameters
1017 .iter()
1018 .map(|parameter_state| parameter_state.parameter.data())
1019 .collect::<Vec<_>>();
1020 let mut indices = (0..self.parameters.len()).collect::<Vec<_>>().into_iter();
1021 while indices.len() >= 4 && self.gate.is_none() {
1022 let batch_indices: [usize; 4] =
1023 std::array::from_fn(|_| indices.next().expect("four indices remain"));
1024 let entries = std::array::from_fn(|batch| {
1025 let index = batch_indices[batch];
1026 AdamWBatchEntry {
1027 parameter: ¶meters[index],
1028 gradient: &gradients[index],
1029 first_moment: &self.parameters[index].first_moment,
1030 second_moment: &self.parameters[index].second_moment,
1031 }
1032 });
1033 adamw_many4_graph(&entries, &state)?;
1034 }
1035 for index in indices {
1036 let parameter_state = &self.parameters[index];
1037 if let Some(flag) = &self.gate {
1038 adamw_gated_graph(
1039 ¶meters[index],
1040 &gradients[index],
1041 ¶meter_state.first_moment,
1042 ¶meter_state.second_moment,
1043 &state,
1044 flag,
1045 )?;
1046 } else {
1047 adamw_graph(
1048 ¶meters[index],
1049 &gradients[index],
1050 ¶meter_state.first_moment,
1051 ¶meter_state.second_moment,
1052 &state,
1053 )?;
1054 }
1055 }
1056 self.graph_state = Some(state);
1057 Ok(())
1058 }
1059
1060 #[must_use]
1065 pub fn parameters(&self) -> Vec<crate::ml::Parameter> {
1066 self
1067 .parameters
1068 .iter()
1069 .map(|state| state.parameter.clone())
1070 .collect()
1071 }
1072
1073 pub fn set_finite_gate(&mut self, flag: &Matrix) -> Result<()> {
1087 if flag.dtype() != DType::F32 || flag.num_elements() != 1 {
1088 return Err(Error::invalid_argument(
1089 "AdamW finite gate requires a single-element F32 flag",
1090 ));
1091 }
1092 if !flag
1093 .runtime()
1094 .same_as(self.parameters[0].parameter.data().runtime())
1095 {
1096 return Err(Error::invalid_argument(
1097 "AdamW finite gate flag must belong to the optimizer runtime",
1098 ));
1099 }
1100 self.gate = Some(flag.clone());
1101 Ok(())
1102 }
1103
1104 pub const fn learning_rate(&self) -> f32 {
1106 self.learning_rate
1107 }
1108
1109 pub fn set_learning_rate(&mut self, learning_rate: f32) -> Result<()> {
1121 if !learning_rate.is_finite() || learning_rate < 0.0 {
1122 return Err(Error::invalid_argument(
1123 "AdamW learning rate must be finite and non-negative",
1124 ));
1125 }
1126 if let Some(state) = &self.graph_state {
1127 state.storage().ensure_ready()?;
1128 state.write_values(&[
1129 self.applied_step_at_boundary()?,
1130 learning_rate.to_bits(),
1131 self.beta1.to_bits(),
1132 self.beta2.to_bits(),
1133 self.epsilon.to_bits(),
1134 self.weight_decay.to_bits(),
1135 ])?;
1136 }
1137 self.learning_rate = learning_rate;
1138 Ok(())
1139 }
1140
1141 pub const fn step_count(&self) -> u32 {
1143 self.step
1144 }
1145
1146 pub(crate) fn applied_step_at_boundary(&self) -> Result<u32> {
1149 if let Some(state) = &self.graph_state
1150 && (self.gate.is_some() || self.applied_step.is_some())
1151 {
1152 return Ok(state.try_read::<u32>()?[0]);
1153 }
1154 Ok(self.applied_step.unwrap_or(self.step))
1155 }
1156
1157 pub(crate) fn belongs_to(&self, runtime: &Runtime) -> bool {
1158 runtime.same_as_handle(self.parameters[0].parameter.data().runtime())
1159 }
1160
1161 pub(crate) fn program_signature(&self) -> Result<AdamWProgramSignature> {
1162 let state = self.graph_state.as_ref().ok_or_else(|| {
1163 Error::failed_precondition("AdamW did not record graph-resident replay state")
1164 })?;
1165 let gradient_ids = self
1166 .parameters
1167 .iter()
1168 .map(|entry| {
1169 entry
1170 .parameter
1171 .gradient()
1172 .map(|gradient| gradient.value_id())
1173 .ok_or_else(|| {
1174 Error::failed_precondition("captured AdamW lost a stable parameter gradient")
1175 })
1176 })
1177 .collect::<Result<Vec<_>>>()?;
1178 Ok(AdamWProgramSignature {
1179 optimizer_id: self.id,
1180 state_id: state.value_id(),
1181 parameter_ids: self
1182 .parameters
1183 .iter()
1184 .map(|entry| entry.parameter.data().value_id())
1185 .collect(),
1186 gradient_ids,
1187 moment_ids: self
1188 .parameters
1189 .iter()
1190 .map(|entry| {
1191 (
1192 entry.first_moment.value_id(),
1193 entry.second_moment.value_id(),
1194 )
1195 })
1196 .collect(),
1197 gate_id: self.gate.as_ref().map(|flag| flag.value_id()),
1198 base_step: self.step,
1199 })
1200 }
1201
1202 pub(crate) fn validate_program_replay(
1203 &self,
1204 signature: &AdamWProgramSignature,
1205 expected_step: u32,
1206 logical_step: u32,
1207 ) -> Result<()> {
1208 let state_matches = self
1209 .graph_state
1210 .as_ref()
1211 .is_some_and(|state| state.value_id() == signature.state_id);
1212 let parameter_ids = self
1213 .parameters
1214 .iter()
1215 .map(|entry| entry.parameter.data().value_id())
1216 .collect::<Vec<_>>();
1217 let gradient_ids = self
1218 .parameters
1219 .iter()
1220 .map(|entry| {
1221 entry
1222 .parameter
1223 .gradient()
1224 .map(|gradient| gradient.value_id())
1225 })
1226 .collect::<Option<Vec<_>>>();
1227 let moment_ids = self
1228 .parameters
1229 .iter()
1230 .map(|entry| {
1231 (
1232 entry.first_moment.value_id(),
1233 entry.second_moment.value_id(),
1234 )
1235 })
1236 .collect::<Vec<_>>();
1237 if self.id != signature.optimizer_id
1238 || self.step != expected_step
1239 || !state_matches
1240 || parameter_ids != signature.parameter_ids
1241 || gradient_ids.as_deref() != Some(signature.gradient_ids.as_slice())
1242 || moment_ids != signature.moment_ids
1243 || self.gate.as_ref().map(|flag| flag.value_id()) != signature.gate_id
1244 {
1245 return Err(Error::failed_precondition(
1246 "AdamW state no longer matches the captured training program",
1247 ));
1248 }
1249 if logical_step > self.step {
1250 for state in &self.parameters {
1251 state.parameter.validate_can_update()?;
1252 }
1253 }
1254 Ok(())
1255 }
1256
1257 pub(crate) fn complete_program_replay(
1258 &mut self,
1259 signature: &AdamWProgramSignature,
1260 logical_step: u32,
1261 ) -> Result<()> {
1262 if logical_step > self.step {
1263 for state in &self.parameters {
1264 state.parameter.mark_updated()?;
1265 }
1266 }
1267 self.step = logical_step;
1268 debug_assert!(self.step > signature.base_step);
1269 Ok(())
1270 }
1271
1272 pub(crate) fn complete_capture_fallback(
1273 &mut self,
1274 signature: &AdamWProgramSignature,
1275 ) -> Result<()> {
1276 let logical_step = signature
1277 .base_step
1278 .checked_add(1)
1279 .ok_or_else(|| Error::resource_exhausted("training step counter exhausted"))?;
1280 self.validate_program_replay(signature, signature.base_step, logical_step)?;
1281 self.complete_program_replay(signature, logical_step)
1282 }
1283
1284 #[allow(dead_code)]
1296 pub(crate) fn complete_captured_step(&mut self) -> Result<()> {
1297 let step = self
1298 .step
1299 .checked_add(1)
1300 .ok_or_else(|| Error::resource_exhausted("AdamW step counter exhausted"))?;
1301 for state in &self.parameters {
1302 state.parameter.mark_updated()?;
1303 }
1304 self.step = step;
1305 Ok(())
1306 }
1307
1308 pub(super) fn checkpoint(&self) -> Result<OptimizerCheckpoint> {
1309 let applied_step = self.applied_step_at_boundary()?;
1310 Ok(OptimizerCheckpoint {
1311 kind: "AdamW",
1312 step: u64::from(self.step),
1313 applied_step: (applied_step != self.step).then_some(u64::from(applied_step)),
1314 learning_rate: self.learning_rate,
1315 beta1: self.beta1,
1316 beta2: self.beta2,
1317 epsilon: self.epsilon,
1318 weight_decay: self.weight_decay,
1319 parameters: self
1320 .parameters
1321 .iter()
1322 .map(|state| state.parameter.clone())
1323 .collect(),
1324 first_state: self
1325 .parameters
1326 .iter()
1327 .map(|state| state.first_moment.clone())
1328 .collect(),
1329 second_state: self
1330 .parameters
1331 .iter()
1332 .map(|state| state.second_moment.clone())
1333 .collect(),
1334 })
1335 }
1336
1337 pub(super) fn validate_checkpoint(&self, checkpoint: &OptimizerRestore) -> Result<()> {
1338 if checkpoint.kind != "AdamW"
1339 || checkpoint.first_state.len() != self.parameters.len()
1340 || checkpoint.second_state.len() != self.parameters.len()
1341 || checkpoint.step > u64::from(u32::MAX)
1342 || checkpoint
1343 .applied_step
1344 .is_some_and(|applied| applied > checkpoint.step)
1345 || !checkpoint.learning_rate.is_finite()
1346 || checkpoint.learning_rate < 0.0
1347 || !checkpoint.beta1.is_finite()
1348 || !checkpoint.beta2.is_finite()
1349 || !checkpoint.epsilon.is_finite()
1350 || checkpoint.epsilon <= 0.0
1351 || !checkpoint.weight_decay.is_finite()
1352 {
1353 return Err(Error::invalid_argument("invalid AdamW checkpoint state"));
1354 }
1355 for ((state, first), second) in self
1356 .parameters
1357 .iter()
1358 .zip(&checkpoint.first_state)
1359 .zip(&checkpoint.second_state)
1360 {
1361 let data = state.parameter.data();
1362 for moment in [first, second] {
1363 if moment.shape() != data.shape()
1364 || moment.dtype() != DType::F32
1365 || !moment.runtime().same_as(data.runtime())
1366 {
1367 return Err(Error::invalid_argument(
1368 "AdamW checkpoint moment contract mismatch",
1369 ));
1370 }
1371 }
1372 }
1373 Ok(())
1374 }
1375
1376 pub(super) fn restore_checkpoint(&mut self, checkpoint: OptimizerRestore) -> Result<()> {
1377 self.validate_checkpoint(&checkpoint)?;
1378 for ((state, first), second) in self
1379 .parameters
1380 .iter_mut()
1381 .zip(checkpoint.first_state)
1382 .zip(checkpoint.second_state)
1383 {
1384 state.first_moment = first;
1385 state.second_moment = second;
1386 }
1387 self.step = checkpoint.step as u32;
1388 self.applied_step = checkpoint.applied_step.map(|step| step as u32);
1389 self.learning_rate = checkpoint.learning_rate;
1390 self.beta1 = checkpoint.beta1;
1391 self.beta2 = checkpoint.beta2;
1392 self.epsilon = checkpoint.epsilon;
1393 self.weight_decay = checkpoint.weight_decay;
1394 self.graph_state = None;
1395 self.gate = None;
1396 Ok(())
1397 }
1398}
1399
1400impl Optimizer for AdamW {
1401 fn zero_grad(&self) {
1402 Self::zero_grad(self);
1403 }
1404
1405 fn step(&mut self) -> Result<()> {
1406 Self::step(self)
1407 }
1408
1409 fn learning_rate(&self) -> f32 {
1410 Self::learning_rate(self)
1411 }
1412
1413 fn set_learning_rate(&mut self, learning_rate: f32) -> Result<()> {
1414 Self::set_learning_rate(self, learning_rate)
1415 }
1416
1417 fn step_count(&self) -> u64 {
1418 u64::from(Self::step_count(self))
1419 }
1420
1421 fn belongs_to(&self, runtime: &Runtime) -> bool {
1422 Self::belongs_to(self, runtime)
1423 }
1424
1425 fn set_finite_gate(&mut self, flag: &Matrix) -> Result<()> {
1426 Self::set_finite_gate(self, flag)
1427 }
1428}
1429
1430impl checkpoint_capability::Persistence for AdamW {
1431 fn checkpoint_state(&self) -> Result<OptimizerCheckpoint> {
1432 Self::checkpoint(self)
1433 }
1434
1435 fn validate_checkpoint_state(&self, state: &OptimizerRestore) -> Result<()> {
1436 Self::validate_checkpoint(self, state)
1437 }
1438
1439 fn restore_checkpoint_state(&mut self, state: OptimizerRestore) -> Result<()> {
1440 Self::restore_checkpoint(self, state)
1441 }
1442}