1use ruxla_core::{Array, Backend, Float, I32, Scalar, Tree, jnp, lax, leaves_as, unflatten_arrays};
11use ruxla_ir::Value;
12
13fn constant<B: Backend, T: Float>(v: f64) -> Scalar<B, T> {
15 Scalar::from(T::from_value(Value::Float(v)))
16}
17
18fn safe_increment<B: Backend>(count: I32<B>) -> I32<B> {
21 lax::select(count.lt(i32::MAX), count + 1, I32::new(i32::MAX))
22}
23
24pub trait GradientTransformation {
27 type State<B: Backend, T: Float>: Tree<B> + Clone;
29
30 fn init<B: Backend, T: Float>(&self, params: &[Array<B, T>]) -> Self::State<B, T>;
32
33 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 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 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
68pub 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#[derive(Clone, Debug)]
86pub struct Chain<A, C>(pub A, pub C);
87
88pub 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#[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
130pub trait Schedule {
133 fn at<B: Backend, T: Float>(&self, count: I32<B>) -> Scalar<B, T>;
135}
136
137#[derive(Clone, Copy, Debug)]
140pub struct LinearSchedule {
141 pub init: f64,
143 pub end: f64,
145 pub transition_steps: i32,
147}
148
149pub 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 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#[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#[derive(Clone, Debug, Tree)]
198pub struct AdamState<B: Backend, T: Float> {
199 pub count: I32<B>,
201 pub mu: Vec<Array<B, T>>,
203 pub nu: Vec<Array<B, T>>,
205}
206
207#[derive(Clone, Copy, Debug)]
209pub struct ScaleByAdam {
210 pub b1: f64,
212 pub b2: f64,
214 pub eps: f64,
216 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 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 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#[derive(Clone, Copy, Debug)]
286pub struct ClipByGlobalNorm(pub f64);
287
288pub fn clip_by_global_norm(max_norm: f64) -> ClipByGlobalNorm {
290 ClipByGlobalNorm(max_norm)
291}
292
293pub 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
326pub fn sgd(learning_rate: f64) -> Scale {
329 Scale(-learning_rate)
330}
331
332pub fn adam(learning_rate: f64) -> Chain<ScaleByAdam, Scale> {
352 Chain(ScaleByAdam::default(), Scale(-learning_rate))
353}
354
355pub fn adam_with_schedule<S: Schedule>(schedule: S) -> Chain<ScaleByAdam, ScaleBySchedule<S>> {
357 Chain(ScaleByAdam::default(), ScaleBySchedule(schedule))
358}