Skip to main content

ruxla_nn/
optim.rs

1//! Optimizers with the computations of Optax's: gradient transformations that
2//! are chained, applied to the gradient, and whose result is added to the
3//! parameters.
4//!
5//! The transformations are generic over the backend, so a training step runs
6//! natively or is traced (and compiled with XLA, inside `jit`). They follow
7//! the operations of Optax 0.2, so that with the same inputs they compute
8//! the same values.
9
10use ruxla_core::{Array, Backend, Float, I32, Scalar, Tree, jnp, lax, leaves_as, unflatten_arrays};
11use ruxla_ir::Value;
12
13/// A constant of type `T`.
14fn constant<B: Backend, T: Float>(v: f64) -> Scalar<B, T> {
15    Scalar::from(T::from_value(Value::Float(v)))
16}
17
18/// `count + 1`, staying at the maximum instead of overflowing
19/// (`optax.safe_increment`).
20fn safe_increment<B: Backend>(count: I32<B>) -> I32<B> {
21    lax::select(count.lt(i32::MAX), count + 1, I32::new(i32::MAX))
22}
23
24/// A transformation of updates (`optax.GradientTransformation`), applied
25/// to the leaves of the parameters, all of type `T`.
26pub trait GradientTransformation {
27    /// The state, for leaves of type `T` on backend `B`.
28    type State<B: Backend, T: Float>: Tree<B> + Clone;
29
30    /// The initial state for parameters with the leaves `params`.
31    fn init<B: Backend, T: Float>(&self, params: &[Array<B, T>]) -> Self::State<B, T>;
32
33    /// Transforms the updates (one per leaf of the parameters) and returns
34    /// the new state.
35    fn update<B: Backend, T: Float>(
36        &self,
37        updates: Vec<Array<B, T>>,
38        state: Self::State<B, T>,
39    ) -> (Vec<Array<B, T>>, Self::State<B, T>);
40
41    /// The initial state for the parameters `params` (any pytree whose
42    /// leaves are of type `T`).
43    ///
44    /// # Panics
45    ///
46    /// Panics if a leaf has another type.
47    fn init_tree<B: Backend, T: Float, P: Tree<B>>(&self, params: &P) -> Self::State<B, T> {
48        self.init(&leaves_as::<B, T, P>(params))
49    }
50
51    /// Transforms the gradient `grads` (a pytree like the parameters) and
52    /// returns the updates, to add to the parameters with
53    /// [`apply_updates`], and the new state.
54    ///
55    /// # Panics
56    ///
57    /// Panics if a leaf has another type.
58    fn update_tree<B: Backend, T: Float, P: Tree<B>>(
59        &self,
60        grads: &P,
61        state: Self::State<B, T>,
62    ) -> (P, Self::State<B, T>) {
63        let (u, s) = self.update(leaves_as::<B, T, P>(grads), state);
64        (unflatten_arrays(grads, u), s)
65    }
66}
67
68/// `params + updates` for each leaf (`optax.apply_updates`).
69///
70/// # Panics
71///
72/// Panics if the pytrees differ in structure or a leaf is not of type `T`.
73pub fn apply_updates<B: Backend, T: Float, P: Tree<B>>(params: &P, updates: &P) -> P {
74    let p = leaves_as::<B, T, P>(params);
75    let u = leaves_as::<B, T, P>(updates);
76    assert_eq!(
77        p.len(),
78        u.len(),
79        "the updates must have the structure of the parameters"
80    );
81    unflatten_arrays(params, p.into_iter().zip(u).map(|(p, u)| p + u).collect())
82}
83
84/// Two transformations applied one after the other (`optax.chain`).
85#[derive(Clone, Debug)]
86pub struct Chain<A, C>(pub A, pub C);
87
88/// Applies `a`, then `c` (`optax.chain(a, c)`).
89pub fn chain<A: GradientTransformation, C: GradientTransformation>(a: A, c: C) -> Chain<A, C> {
90    Chain(a, c)
91}
92
93impl<A: GradientTransformation, C: GradientTransformation> GradientTransformation for Chain<A, C> {
94    type State<B: Backend, T: Float> = (A::State<B, T>, C::State<B, T>);
95
96    fn init<B: Backend, T: Float>(&self, params: &[Array<B, T>]) -> Self::State<B, T> {
97        (self.0.init(params), self.1.init(params))
98    }
99
100    fn update<B: Backend, T: Float>(
101        &self,
102        updates: Vec<Array<B, T>>,
103        (s0, s1): Self::State<B, T>,
104    ) -> (Vec<Array<B, T>>, Self::State<B, T>) {
105        let (u, s0) = self.0.update(updates, s0);
106        let (u, s1) = self.1.update(u, s1);
107        (u, (s0, s1))
108    }
109}
110
111/// Multiplies the updates by a constant (`optax.scale`).
112#[derive(Clone, Copy, Debug)]
113pub struct Scale(pub f64);
114
115impl GradientTransformation for Scale {
116    type State<B: Backend, T: Float> = ();
117
118    fn init<B: Backend, T: Float>(&self, _: &[Array<B, T>]) {}
119
120    fn update<B: Backend, T: Float>(
121        &self,
122        updates: Vec<Array<B, T>>,
123        (): (),
124    ) -> (Vec<Array<B, T>>, ()) {
125        let s = constant::<B, T>(self.0);
126        (updates.into_iter().map(|u| s * u).collect(), ())
127    }
128}
129
130/// A learning rate that depends on the number of updates so far
131/// (`optax.Schedule`).
132pub trait Schedule {
133    /// The learning rate at update `count` (counted from 0).
134    fn at<B: Backend, T: Float>(&self, count: I32<B>) -> Scalar<B, T>;
135}
136
137/// `init` decreasing (or increasing) linearly to `end` over
138/// `transition_steps` updates, then constant (`optax.linear_schedule`).
139#[derive(Clone, Copy, Debug)]
140pub struct LinearSchedule {
141    /// The initial value.
142    pub init: f64,
143    /// The final value.
144    pub end: f64,
145    /// The number of updates over which the value changes.
146    pub transition_steps: i32,
147}
148
149/// See [`LinearSchedule`].
150pub fn linear_schedule(init: f64, end: f64, transition_steps: i32) -> LinearSchedule {
151    LinearSchedule {
152        init,
153        end,
154        transition_steps,
155    }
156}
157
158impl Schedule for LinearSchedule {
159    fn at<B: Backend, T: Float>(&self, count: I32<B>) -> Scalar<B, T> {
160        if self.transition_steps <= 0 {
161            return constant(self.init);
162        }
163        // `optax.polynomial_schedule` with power 1.
164        let c = count.max(0).min(self.transition_steps);
165        let frac = constant::<B, T>(1.0)
166            - c.cast::<T>() / constant::<B, T>(f64::from(self.transition_steps));
167        constant::<B, T>(self.init - self.end) * frac + constant::<B, T>(self.end)
168    }
169}
170
171/// Multiplies the updates by minus the learning rate of the schedule
172/// (`optax.scale_by_learning_rate` with a schedule).
173#[derive(Clone, Debug)]
174pub struct ScaleBySchedule<S>(pub S);
175
176impl<S: Schedule> GradientTransformation for ScaleBySchedule<S> {
177    type State<B: Backend, T: Float> = I32<B>;
178
179    fn init<B: Backend, T: Float>(&self, _: &[Array<B, T>]) -> I32<B> {
180        I32::new(0)
181    }
182
183    fn update<B: Backend, T: Float>(
184        &self,
185        updates: Vec<Array<B, T>>,
186        count: I32<B>,
187    ) -> (Vec<Array<B, T>>, I32<B>) {
188        let step = constant::<B, T>(-1.0) * self.0.at::<B, T>(count);
189        (
190            updates.into_iter().map(|u| step * u).collect(),
191            safe_increment(count),
192        )
193    }
194}
195
196/// The state of [`ScaleByAdam`] (`optax.ScaleByAdamState`).
197#[derive(Clone, Debug, Tree)]
198pub struct AdamState<B: Backend, T: Float> {
199    /// The number of updates.
200    pub count: I32<B>,
201    /// The first moments.
202    pub mu: Vec<Array<B, T>>,
203    /// The second moments.
204    pub nu: Vec<Array<B, T>>,
205}
206
207/// Adam's rescaling of the updates (`optax.scale_by_adam`).
208#[derive(Clone, Copy, Debug)]
209pub struct ScaleByAdam {
210    /// The decay of the first moments.
211    pub b1: f64,
212    /// The decay of the second moments.
213    pub b2: f64,
214    /// Added to the denominator.
215    pub eps: f64,
216    /// Added to the second moments inside the square root.
217    pub eps_root: f64,
218}
219
220impl Default for ScaleByAdam {
221    fn default() -> Self {
222        Self {
223            b1: 0.9,
224            b2: 0.999,
225            eps: 1e-8,
226            eps_root: 0.0,
227        }
228    }
229}
230
231impl GradientTransformation for ScaleByAdam {
232    type State<B: Backend, T: Float> = AdamState<B, T>;
233
234    fn init<B: Backend, T: Float>(&self, params: &[Array<B, T>]) -> AdamState<B, T> {
235        let zeros: Vec<Array<B, T>> = params
236            .iter()
237            .map(|p| jnp::zeros::<B, T>(p.shape()))
238            .collect();
239        AdamState {
240            count: I32::new(0),
241            mu: zeros.clone(),
242            nu: zeros,
243        }
244    }
245
246    fn update<B: Backend, T: Float>(
247        &self,
248        updates: Vec<Array<B, T>>,
249        state: AdamState<B, T>,
250    ) -> (Vec<Array<B, T>>, AdamState<B, T>) {
251        let c = constant::<B, T>;
252        let (b1, b2) = (c(self.b1), c(self.b2));
253        // `optax.tree.update_moment` and `update_moment_per_elem_norm`.
254        let mu: Vec<Array<B, T>> = updates
255            .iter()
256            .zip(&state.mu)
257            .map(|(g, m)| c(1.0 - self.b1) * g + b1 * m)
258            .collect();
259        let nu: Vec<Array<B, T>> = updates
260            .iter()
261            .zip(&state.nu)
262            .map(|(g, v)| c(1.0 - self.b2) * g.integer_pow(2) + b2 * v)
263            .collect();
264        let count = safe_increment(state.count);
265        // `optax.tree.bias_correction`: `t / (1 - decay ** count)`, where
266        // XLA computes the power in floating point.
267        let n = count.cast::<T>();
268        let bc1 = c(1.0) - b1.pow(n);
269        let bc2 = c(1.0) - b2.pow(n);
270        let out = mu
271            .iter()
272            .zip(&nu)
273            .map(|(m, v)| {
274                let m_hat = m / bc1;
275                let v_hat = v / bc2;
276                m_hat / (jnp::sqrt(&(v_hat + c(self.eps_root))) + c(self.eps))
277            })
278            .collect();
279        (out, AdamState { count, mu, nu })
280    }
281}
282
283/// Scales the updates so that their global norm is at most `max_norm`
284/// (`optax.clip_by_global_norm`).
285#[derive(Clone, Copy, Debug)]
286pub struct ClipByGlobalNorm(pub f64);
287
288/// See [`ClipByGlobalNorm`].
289pub fn clip_by_global_norm(max_norm: f64) -> ClipByGlobalNorm {
290    ClipByGlobalNorm(max_norm)
291}
292
293/// The L2 norm of all the leaves together (`optax.tree.norm`).
294pub fn global_norm<B: Backend, T: Float>(leaves: &[Array<B, T>]) -> Scalar<B, T> {
295    let mut sq = constant::<B, T>(0.0);
296    for l in leaves {
297        sq = sq + jnp::sum(l.integer_pow(2), jnp::ALL).to_scalar();
298    }
299    sq.sqrt()
300}
301
302impl GradientTransformation for ClipByGlobalNorm {
303    type State<B: Backend, T: Float> = ();
304
305    fn init<B: Backend, T: Float>(&self, _: &[Array<B, T>]) {}
306
307    fn update<B: Backend, T: Float>(
308        &self,
309        updates: Vec<Array<B, T>>,
310        (): (),
311    ) -> (Vec<Array<B, T>>, ()) {
312        let norm = global_norm(&updates);
313        let max = constant::<B, T>(self.0);
314        let trigger = norm.lt(max);
315        let out = updates
316            .into_iter()
317            .map(|t| {
318                let clipped = t.clone() / norm * max;
319                jnp::where_(trigger, t, clipped)
320            })
321            .collect();
322        (out, ())
323    }
324}
325
326/// Stochastic gradient descent with a constant learning rate (`optax.sgd`
327/// without momentum).
328pub fn sgd(learning_rate: f64) -> Scale {
329    Scale(-learning_rate)
330}
331
332/// Adam with a constant learning rate (`optax.adam`); set the other
333/// hyperparameters on the result's first part.
334///
335/// # Examples
336///
337/// ```
338/// use ruxla_core::{Array, Native};
339/// use ruxla_nn::optim::{GradientTransformation, adam, apply_updates};
340///
341/// let params = (Array::<Native, f32>::from_vec(vec![1.0, 2.0], [2]),);
342/// let opt = adam(0.1);
343/// let state = opt.init_tree::<Native, f32, _>(&params);
344/// let grads = (Array::<Native, f32>::from_vec(vec![0.5, -0.5], [2]),);
345/// let (updates, _state) = opt.update_tree(&grads, state);
346/// let params = apply_updates::<Native, f32, _>(&params, &updates);
347/// // The first step of Adam moves each parameter by about the learning
348/// // rate; the values are those of Optax.
349/// assert_eq!(params.0.to_vec(), [0.9000007, 2.0999994]);
350/// ```
351pub fn adam(learning_rate: f64) -> Chain<ScaleByAdam, Scale> {
352    Chain(ScaleByAdam::default(), Scale(-learning_rate))
353}
354
355/// Adam with a learning rate schedule (`optax.adam` with a schedule).
356pub fn adam_with_schedule<S: Schedule>(schedule: S) -> Chain<ScaleByAdam, ScaleBySchedule<S>> {
357    Chain(ScaleByAdam::default(), ScaleBySchedule(schedule))
358}