oa/ml/optim/optimizer.rs
1//! Shared optimizer contracts, state types, and trait implementations.
2//!
3//! Every concrete optimizer struct lives in its own sibling module and imports
4//! from here. This file is the analog of `nn/module.rs` for the optimizer
5//! subsystem — it owns the common vocabulary that all optimizers share.
6
7use std::sync::atomic::{AtomicU64, Ordering};
8
9use crate::{Error, Matrix, Result, Runtime};
10
11use crate::ml::Parameter;
12
13// ---------------------------------------------------------------------------
14// Public contracts
15// ---------------------------------------------------------------------------
16
17/// Common behavior exposed by an OA optimizer to training policy.
18///
19/// This contract deliberately excludes captured-program and persistence
20/// internals. Those capabilities depend on optimizer-specific state and are
21/// admitted separately only when their complete implementation exists.
22pub trait Optimizer {
23 /// Discard every currently accumulated parameter gradient.
24 fn zero_grad(&self);
25
26 /// Record one logical parameter update.
27 ///
28 /// # Errors
29 ///
30 /// Returns an optimizer, validation, allocation, or runtime recording error.
31 fn step(&mut self) -> Result<()>;
32
33 /// Return the learning rate used by the next optimizer step.
34 fn learning_rate(&self) -> f32;
35
36 /// Set the learning rate used by subsequent optimizer steps.
37 ///
38 /// # Errors
39 ///
40 /// Returns an error when the value is outside the optimizer's contract or
41 /// optimizer state cannot be updated safely.
42 fn set_learning_rate(&mut self, learning_rate: f32) -> Result<()>;
43
44 /// Return the number of completed logical optimizer steps.
45 fn step_count(&self) -> u64;
46
47 /// Return whether this optimizer can participate in work owned by `runtime`.
48 fn belongs_to(&self, runtime: &Runtime) -> bool;
49
50 /// Bind a device-resident finite flag gating captured updates.
51 ///
52 /// The flag is a same-runtime FP32 single-element `Matrix` written by a
53 /// gradient scaler's device check. When a bound optimizer records its
54 /// step inside an `Runtime::capture` program, the update kernels read the
55 /// flag at replay time: a nonzero flag applies the normal update and a
56 /// zero flag freezes parameters, moments, and the device step counter
57 /// exactly, so AMP overflow handling replays inside one captured
58 /// program without a mid-step host decision. Eager steps ignore the
59 /// binding; the host-side scaler gate owns that path.
60 ///
61 /// # Errors
62 ///
63 /// Returns an error when the optimizer does not admit gated captured
64 /// updates or the flag contract is violated.
65 fn set_finite_gate(&mut self, flag: &Matrix) -> Result<()> {
66 let _ = flag;
67 Err(Error::unimplemented(
68 "optimizer does not admit a captured finite gate",
69 ))
70 }
71}
72
73/// Optimizer with a complete native `.oam` save-and-restore contract.
74///
75/// This capability is sealed because persistence must remain synchronized with
76/// OA's versioned model-file codec. Custom optimizers can implement
77/// [`Optimizer`] for eager training without claiming wire compatibility.
78#[allow(private_bounds)]
79pub trait CheckpointOptimizer: Optimizer + checkpoint_capability::Persistence {}
80
81impl<T> CheckpointOptimizer for T where T: Optimizer + checkpoint_capability::Persistence {}
82
83// ---------------------------------------------------------------------------
84// Checkpoint wire types
85// ---------------------------------------------------------------------------
86
87pub struct OptimizerCheckpoint {
88 pub(crate) kind: &'static str,
89 pub(crate) step: u64,
90 pub(crate) applied_step: Option<u64>,
91 pub(crate) learning_rate: f32,
92 pub(crate) beta1: f32,
93 pub(crate) beta2: f32,
94 pub(crate) epsilon: f32,
95 pub(crate) weight_decay: f32,
96 pub(crate) parameters: Vec<Parameter>,
97 pub(crate) first_state: Vec<Matrix>,
98 pub(crate) second_state: Vec<Matrix>,
99}
100
101pub struct OptimizerRestore {
102 pub(crate) kind: String,
103 pub(crate) step: u64,
104 pub(crate) applied_step: Option<u64>,
105 pub(crate) learning_rate: f32,
106 pub(crate) beta1: f32,
107 pub(crate) beta2: f32,
108 pub(crate) epsilon: f32,
109 pub(crate) weight_decay: f32,
110 pub(crate) first_state: Vec<Matrix>,
111 pub(crate) second_state: Vec<Matrix>,
112}
113
114pub(super) mod checkpoint_capability {
115 use super::{OptimizerCheckpoint, OptimizerRestore};
116 use crate::Result;
117
118 pub trait Persistence {
119 fn checkpoint_state(&self) -> Result<OptimizerCheckpoint>;
120 fn validate_checkpoint_state(&self, state: &OptimizerRestore) -> Result<()>;
121 fn restore_checkpoint_state(&mut self, state: OptimizerRestore) -> Result<()>;
122 }
123}
124
125// ---------------------------------------------------------------------------
126// Shared per-parameter state types reused across optimizer modules
127// ---------------------------------------------------------------------------
128
129pub(super) struct MomentParameterState {
130 pub(super) parameter: Parameter,
131 pub(super) first_moment: Matrix,
132 pub(super) second_moment: Matrix,
133}
134
135pub(super) struct SgdParameterState {
136 pub(super) parameter: Parameter,
137 pub(super) momentum: Option<Matrix>,
138}
139
140pub(super) struct MuonParameterState {
141 pub(super) parameter: Parameter,
142 pub(super) momentum: Matrix,
143}
144
145// ---------------------------------------------------------------------------
146// Stable identity counter for AdamW graph capture
147// ---------------------------------------------------------------------------
148
149pub(super) fn next_optimizer_id() -> Result<u64> {
150 static NEXT_OPTIMIZER_ID: AtomicU64 = AtomicU64::new(1);
151 NEXT_OPTIMIZER_ID
152 .try_update(Ordering::Relaxed, Ordering::Relaxed, |value| {
153 (value != u64::MAX).then_some(value + 1)
154 })
155 .map_err(|_| Error::resource_exhausted("optimizer identity exhausted"))
156}
157
158// ---------------------------------------------------------------------------
159// NoOpOptimizer — lives here because it has no submodule of its own
160// ---------------------------------------------------------------------------
161
162/// Optimizer for externally authored parameter updates.
163///
164/// `NoOpOptimizer` lets callers use [`crate::ml::Training`] for cadence,
165/// metrics, and callbacks while the step body owns all parameter mutation.
166#[derive(Clone, Copy, Debug)]
167pub struct NoOpOptimizer {
168 learning_rate: f32,
169}
170
171impl NoOpOptimizer {
172 /// Construct a no-op optimizer with the requested policy-visible rate.
173 ///
174 /// # Errors
175 ///
176 /// Returns an error when `learning_rate` is not finite and non-negative.
177 pub fn new(learning_rate: f32) -> Result<Self> {
178 if !learning_rate.is_finite() || learning_rate < 0.0 {
179 return Err(Error::invalid_argument(
180 "no-op optimizer learning rate must be finite and non-negative",
181 ));
182 }
183 Ok(Self { learning_rate })
184 }
185}
186
187impl Default for NoOpOptimizer {
188 fn default() -> Self {
189 Self { learning_rate: 0.0 }
190 }
191}
192
193impl Optimizer for NoOpOptimizer {
194 fn zero_grad(&self) {}
195
196 fn step(&mut self) -> Result<()> {
197 Ok(())
198 }
199
200 fn learning_rate(&self) -> f32 {
201 self.learning_rate
202 }
203
204 fn set_learning_rate(&mut self, learning_rate: f32) -> Result<()> {
205 if !learning_rate.is_finite() || learning_rate < 0.0 {
206 return Err(Error::invalid_argument(
207 "no-op optimizer learning rate must be finite and non-negative",
208 ));
209 }
210 self.learning_rate = learning_rate;
211 Ok(())
212 }
213
214 fn step_count(&self) -> u64 {
215 0
216 }
217
218 fn belongs_to(&self, _runtime: &Runtime) -> bool {
219 true
220 }
221}