Skip to main content

ruxla_core/
control.rs

1//! Control flow: real branches and loops on `Native`, `cond`, `while`, and
2//! `scan` primitives on `Trace`.
3
4use std::sync::Arc;
5
6use ruxla_ir::{AVal, Params, Var};
7use ruxla_kernels::Element;
8use ruxla_prims as p;
9
10use crate::backend::{Backend, Trace};
11use crate::trace::{self, TraceRef, trace_function};
12use crate::tree::{Tree, leaves};
13use crate::value::{Array, Bool, I32, Scalar};
14
15/// `if pred { on_true } else { on_false }` for scalars (`lax.select`). Both
16/// operands are computed; use [`cond`] to skip work.
17pub fn select<B: Backend, T: Element>(
18    pred: Bool<B>,
19    on_true: impl Into<Scalar<B, T>>,
20    on_false: impl Into<Scalar<B, T>>,
21) -> Scalar<B, T> {
22    Scalar(B::select::<T>(pred.0, on_true.into().0, on_false.into().0))
23}
24
25/// Calls `true_fn(operand)` if `pred` holds and `false_fn(operand)`
26/// otherwise (`lax.cond`). On `Native` this is a real branch.
27///
28/// # Examples
29///
30/// ```
31/// use ruxla_core::{Backend, F32, Native, lax};
32///
33/// fn relu<B: Backend>(x: F32<B>) -> F32<B> {
34///     lax::cond(x.gt(0.0), |x| x, |_| F32::new(0.0), x)
35/// }
36/// assert_eq!(relu::<Native>(F32::new(-2.0)).value(), 0.0);
37/// ```
38pub fn cond<B: Backend, S: Tree<B>, R: Tree<B>>(
39    pred: Bool<B>,
40    true_fn: impl Fn(S) -> R,
41    false_fn: impl Fn(S) -> R,
42    operand: S,
43) -> R {
44    B::cond(pred.cast::<i32>(), &[&false_fn, &true_fn], operand)
45}
46
47/// Calls `branches[index]` on `operand`, with the index clamped to the
48/// branches (`lax.switch`).
49///
50/// # Panics
51///
52/// Panics if there are no branches.
53pub fn switch<B: Backend, S: Tree<B>, R: Tree<B>>(
54    index: I32<B>,
55    branches: &[&dyn Fn(S) -> R],
56    operand: S,
57) -> R {
58    assert!(!branches.is_empty(), "switch needs at least one branch");
59    let lo = Array::<B, i32>::from(Scalar::new(0));
60    let hi = Array::<B, i32>::from(Scalar::new(branches.len() as i32 - 1));
61    let clamped = Array::<B, i32>(B::a_clamp::<i32>(&lo.0, &index.to_array().0, &hi.0)).to_scalar();
62    B::cond(clamped, branches, operand)
63}
64
65impl<B: Backend, T: Element> From<Scalar<B, T>> for Array<B, T> {
66    fn from(s: Scalar<B, T>) -> Self {
67        s.to_array()
68    }
69}
70
71/// Repeats `body_fn` while `cond_fn` holds (`lax.while_loop`).
72///
73/// # Examples
74///
75/// ```
76/// use ruxla_core::{Backend, I32, Native, lax};
77///
78/// fn collatz_steps<B: Backend>(n: I32<B>) -> I32<B> {
79///     let (_, steps) = lax::while_loop(
80///         |(n, _): &(I32<B>, I32<B>)| n.gt(1),
81///         |(n, s)| (lax::select((n % 2).eq(0), n / 2, n * 3 + 1), s + 1),
82///         (n, I32::new(0)),
83///     );
84///     steps
85/// }
86/// assert_eq!(collatz_steps::<Native>(I32::new(27)).value(), 111);
87/// ```
88pub fn while_loop<B: Backend, C: Tree<B>>(
89    cond_fn: impl Fn(&C) -> Bool<B>,
90    body_fn: impl Fn(C) -> C,
91    init: C,
92) -> C {
93    B::while_loop(&cond_fn, &body_fn, init)
94}
95
96/// `for i in lo..hi { state = body(i, state) }` (`lax.fori_loop`). The
97/// bounds are Rust integers or values. On `Trace`, as in JAX, this is a
98/// `scan` when both bounds are static, and a `while` otherwise.
99pub fn fori_loop<B: Backend, C: Tree<B>>(
100    lo: impl Into<I32<B>>,
101    hi: impl Into<I32<B>>,
102    body: impl Fn(I32<B>, C) -> C,
103    init: C,
104) -> C {
105    B::fori_loop(lo.into(), hi.into(), &body, init)
106}
107
108/// A loop over the leading dimension of the arrays of `xs`: returns the
109/// final carry and the outputs stacked along a new leading dimension
110/// (`lax.scan`). `length` must match the leading dimension of `xs` (and is
111/// the number of iterations when `xs` has no arrays).
112pub fn scan<B: Backend, C: Tree<B>, X: Tree<B>, Y: Tree<B>>(
113    f: impl Fn(C, X) -> (C, Y),
114    init: C,
115    xs: X,
116    length: usize,
117) -> (C, Y) {
118    B::scan(&f, init, xs, length, false)
119}
120
121/// [`scan`] from the end.
122pub fn scan_reverse<B: Backend, C: Tree<B>, X: Tree<B>, Y: Tree<B>>(
123    f: impl Fn(C, X) -> (C, Y),
124    init: C,
125    xs: X,
126    length: usize,
127) -> (C, Y) {
128    B::scan(&f, init, xs, length, true)
129}
130
131fn avals(refs: &[TraceRef]) -> Vec<AVal> {
132    refs.iter().map(|&r| trace::aval(r)).collect()
133}
134
135pub(crate) fn trace_cond<S: Tree<Trace>, R: Tree<Trace>>(
136    index: I32<Trace>,
137    branches: &[&dyn Fn(S) -> R],
138    operand: S,
139) -> R {
140    let ops = leaves(&operand);
141    let in_avals = avals(&ops);
142    let mut out_template: Option<R> = None;
143    let traced: Vec<_> = branches
144        .iter()
145        .map(|b| {
146            trace_function(&in_avals, |args| {
147                let op = operand.unflatten_like(&mut args.iter().copied());
148                let r = b(op);
149                let l = leaves(&r);
150                out_template = Some(r);
151                l
152            })
153        })
154        .collect();
155    // Every branch takes the values captured by any branch.
156    let consts: Vec<TraceRef> = traced
157        .iter()
158        .flat_map(|t| t.captured.iter().copied())
159        .collect();
160    let functions: Vec<Arc<ruxla_ir::Function>> = traced
161        .iter()
162        .enumerate()
163        .map(|(k, t)| {
164            let n = t.captured.len();
165            let mut f = t.function.clone();
166            let own = f.invars.drain(..n).collect::<Vec<Var>>();
167            let mut invars = Vec::new();
168            for (j, u) in traced.iter().enumerate() {
169                if j == k {
170                    invars.extend(own.iter().cloned());
171                } else {
172                    invars.extend(u.captured.iter().map(|&r| Var::new(trace::aval(r))));
173                }
174            }
175            invars.append(&mut f.invars);
176            f.invars = invars;
177            Arc::new(f)
178        })
179        .collect();
180    let mut inputs = vec![index.0];
181    inputs.extend(consts);
182    inputs.extend(ops);
183    let outs = trace::bind(
184        p::COND,
185        &inputs,
186        Params::Cond {
187            branches: functions,
188        },
189    );
190    out_template
191        .expect("at least one branch")
192        .unflatten_like(&mut outs.into_iter())
193}
194
195/// `select_tree(pred, &on_true(), &on_false())`, computing only the chosen
196/// side when the backend can branch (natively); traced, both sides are
197/// computed and selected, which gives the same IR as `lax.select` in JAX.
198///
199/// Use it where a value is computed and then discarded unless a condition
200/// holds (a reset at the end of an episode, for example); the closures must
201/// be pure, so that skipping one does not change the result.
202///
203/// # Examples
204///
205/// ```
206/// use ruxla_core::{F32, Native, lax};
207///
208/// let done = ruxla_core::Bool::<Native>::new(false);
209/// let x = lax::select_with(done, || F32::new(0.0), || F32::new(1.5));
210/// assert_eq!(x.value(), 1.5);
211/// ```
212#[inline]
213pub fn select_with<B: Backend, T: Tree<B>>(
214    pred: Bool<B>,
215    on_true: impl FnOnce() -> T,
216    on_false: impl FnOnce() -> T,
217) -> T {
218    if let Some(p) = B::branch_value(pred) {
219        if p { on_true() } else { on_false() }
220    } else {
221        crate::tree::select_tree(pred, &on_true(), &on_false())
222    }
223}
224
225/// [`select_with`] whose sides take `operand`: natively, the chosen side
226/// gets it by value (so that it can update arrays in place, without the
227/// copy that a shared array needs); traced, each side gets a copy, and the
228/// results are selected (the same IR as `lax.select` of both sides in JAX).
229///
230/// # Examples
231///
232/// ```
233/// use ruxla_core::{Array, Bool, Native, lax};
234///
235/// let grid = Array::<Native, f32>::from_vec(vec![0.0; 4], [2, 2]);
236/// let left = Bool::<Native>::new(true);
237/// let grid = lax::select_with_operand(
238///     left,
239///     grid,
240///     |g| g.into_at((.., 0i64)).set(1.0f32),
241///     |g| g.into_at((.., 1i64)).set(1.0f32),
242/// );
243/// assert_eq!(grid.to_vec(), [1.0, 0.0, 1.0, 0.0]);
244/// ```
245#[inline]
246pub fn select_with_operand<B: Backend, S: Clone, T: Tree<B>>(
247    pred: Bool<B>,
248    operand: S,
249    on_true: impl FnOnce(S) -> T,
250    on_false: impl FnOnce(S) -> T,
251) -> T {
252    if let Some(p) = B::branch_value(pred) {
253        if p {
254            on_true(operand)
255        } else {
256            on_false(operand)
257        }
258    } else {
259        crate::tree::select_tree(pred, &on_true(operand.clone()), &on_false(operand))
260    }
261}
262
263/// `f(primals)`, whose derivative in forward mode (and, by linearization,
264/// in reverse mode) is given by the rule `jvp`, like `jax.custom_jvp`.
265///
266/// `jvp` takes the primals and their tangents (of the same structure; the
267/// tangents of non-float values are zeros) and returns the outputs and their
268/// tangents, which must be linear in the input tangents for reverse mode.
269/// Natively, and when the function is not differentiated, `f` is computed.
270/// Values that the functions capture are not differentiated.
271///
272/// # Examples
273///
274/// ```
275/// use ruxla_core::{F32, Trace, grad, lax};
276///
277/// // log(1 + e^x), with the derivative computed as sigmoid(x) * t.
278/// fn softplus<B: ruxla_core::Backend>(x: F32<B>) -> F32<B> {
279///     lax::custom_jvp(
280///         |x: F32<B>| (x.exp() + 1.0).ln(),
281///         |x: F32<B>, t: F32<B>| ((x.exp() + 1.0).ln(), t / ((-x).exp() + 1.0)),
282///         x,
283///     )
284/// }
285/// assert_eq!(softplus(F32::<ruxla_core::Native>::new(0.0)).value(), 2f32.ln());
286/// let g = grad(|x: F32<Trace>, (): ()| softplus(x)).call(&F32::new(0.0), &());
287/// assert_eq!(g.value(), 0.5);
288/// ```
289pub fn custom_jvp<B: Backend, I: Tree<B>, O: Tree<B>>(
290    f: impl Fn(I) -> O,
291    jvp: impl Fn(I, I) -> (O, O),
292    primals: I,
293) -> O {
294    B::custom_jvp(&f, &jvp, primals)
295}
296
297/// `f(primals)`, whose derivative in reverse mode is given by `fwd` and
298/// `bwd`, like `jax.custom_vjp`.
299///
300/// `fwd` returns the outputs and residuals `R`; `bwd` takes the residuals
301/// and the cotangents of the outputs, and returns the cotangents of the
302/// primals. `bwd` must not capture traced values (return them from `fwd`).
303/// Forward-mode differentiation of the result is not supported, as in JAX.
304///
305/// # Examples
306///
307/// ```
308/// use ruxla_core::{F32, Trace, grad, lax};
309///
310/// // The identity in the forward pass, with gradients clipped to [-1, 1].
311/// fn clip_gradient<B: ruxla_core::Backend>(x: F32<B>) -> F32<B> {
312///     lax::custom_vjp(|x| x, |x| (x, ()), |(), g: F32<B>| g.max(-1.0).min(1.0), x)
313/// }
314/// let g = grad(|x: F32<Trace>, (): ()| clip_gradient(x * 3.0)).call(&F32::new(1.0), &());
315/// assert_eq!(g.value(), 3.0); // 3 * clip(1)
316/// ```
317pub fn custom_vjp<B: Backend, I: Tree<B>, O: Tree<B>, R: Tree<B>>(
318    f: impl Fn(I) -> O,
319    fwd: impl Fn(I) -> (O, R),
320    bwd: impl Fn(R, O) -> I,
321    primals: I,
322) -> O {
323    B::custom_vjp(&f, &fwd, &bwd, primals)
324}
325
326/// `f(input)`, whose intermediate values reverse-mode differentiation
327/// recomputes from the inputs instead of storing (`jax.checkpoint`).
328pub fn checkpoint<B: Backend, I: Tree<B>, O: Tree<B>>(f: impl Fn(I) -> O, input: I) -> O {
329    B::checkpoint(&f, input)
330}
331
332/// Gives traced functions the values that any of them captured: each
333/// function takes all the captured values first (in the order of
334/// `traced`), then its own arguments.
335fn share_captured(traced: &[&trace::Traced]) -> (Vec<TraceRef>, Vec<ruxla_ir::Function>) {
336    let consts: Vec<TraceRef> = traced
337        .iter()
338        .flat_map(|t| t.captured.iter().copied())
339        .collect();
340    let functions = traced
341        .iter()
342        .enumerate()
343        .map(|(k, t)| {
344            let mut f = t.function.clone();
345            let own: Vec<Var> = f.invars.drain(..t.captured.len()).collect();
346            let mut invars = Vec::new();
347            for (j, u) in traced.iter().enumerate() {
348                if j == k {
349                    invars.extend(own.iter().cloned());
350                } else {
351                    invars.extend(u.captured.iter().map(|&r| Var::new(trace::aval(r))));
352                }
353            }
354            invars.append(&mut f.invars);
355            f.invars = invars;
356            f
357        })
358        .collect();
359    (consts, functions)
360}
361
362pub(crate) fn trace_custom_jvp<I: Tree<Trace>, O: Tree<Trace>>(
363    f: &dyn Fn(I) -> O,
364    jvp: &dyn Fn(I, I) -> (O, O),
365    primals: I,
366) -> O {
367    let args = leaves(&primals);
368    let in_avals = avals(&args);
369    let mut out: Option<O> = None;
370    let tf = trace_function(&in_avals, |refs| {
371        let o = f(primals.unflatten_like(&mut refs.iter().copied()));
372        let l = leaves(&o);
373        out = Some(o);
374        l
375    });
376    let mut jvp_avals = in_avals.clone();
377    jvp_avals.extend(in_avals.iter().cloned());
378    let tj = trace_function(&jvp_avals, |refs| {
379        let mut it = refs.iter().copied();
380        let x = primals.unflatten_like(&mut it);
381        let t = primals.unflatten_like(&mut it);
382        let (o, to) = jvp(x, t);
383        let mut l = leaves(&o);
384        l.extend(leaves(&to));
385        l
386    });
387    let (consts, mut fs) = share_captured(&[&tf, &tj]);
388    let jvp_fn = fs.pop().expect("two functions");
389    let call = fs.pop().expect("two functions");
390    assert_eq!(
391        jvp_fn.out_avals()[..call.outvars.len()],
392        call.out_avals()[..],
393        "custom_jvp: the rule must return outputs of the types of the function's"
394    );
395    let num_consts = consts.len();
396    let mut inputs = consts;
397    inputs.extend(args);
398    let outs = trace::bind(
399        p::CUSTOM_JVP_CALL,
400        &inputs,
401        Params::CustomJvp {
402            call: Arc::new(call),
403            jvp: Arc::new(jvp_fn),
404            num_consts,
405        },
406    );
407    out.expect("the function was called")
408        .unflatten_like(&mut outs.into_iter())
409}
410
411pub(crate) fn trace_custom_vjp<I: Tree<Trace>, O: Tree<Trace>, R: Tree<Trace>>(
412    f: &dyn Fn(I) -> O,
413    fwd: &dyn Fn(I) -> (O, R),
414    bwd: &dyn Fn(R, O) -> I,
415    primals: I,
416) -> O {
417    let args = leaves(&primals);
418    let in_avals = avals(&args);
419    let mut out: Option<O> = None;
420    let tf = trace_function(&in_avals, |refs| {
421        let o = f(primals.unflatten_like(&mut refs.iter().copied()));
422        let l = leaves(&o);
423        out = Some(o);
424        l
425    });
426    let out = out.expect("the function was called");
427    let mut residuals: Option<R> = None;
428    let tw = trace_function(&in_avals, |refs| {
429        let (o, r) = fwd(primals.unflatten_like(&mut refs.iter().copied()));
430        let mut l = leaves(&o);
431        l.extend(leaves(&r));
432        residuals = Some(r);
433        l
434    });
435    let residuals = residuals.expect("the function was called");
436    // The residuals' types, from the forward function (their values belong
437    // to its finished trace).
438    let n_out = tf.function.outvars.len();
439    let mut bwd_avals = tw.function.out_avals()[n_out..].to_vec();
440    bwd_avals.extend(tf.function.out_avals());
441    let tb = trace_function(&bwd_avals, |refs| {
442        let mut it = refs.iter().copied();
443        let r = residuals.unflatten_like(&mut it);
444        let g = out.unflatten_like(&mut it);
445        leaves(&bwd(r, g))
446    });
447    assert!(
448        tb.captured.is_empty(),
449        "custom_vjp: bwd must not capture traced values; return them as residuals from fwd"
450    );
451    assert_eq!(
452        tb.function.out_avals(),
453        in_avals,
454        "custom_vjp: bwd must return cotangents of the types of the primals"
455    );
456    let (consts, mut fs) = share_captured(&[&tf, &tw]);
457    let fwd_fn = fs.pop().expect("two functions");
458    let call = fs.pop().expect("two functions");
459    let num_consts = consts.len();
460    let mut inputs = consts;
461    inputs.extend(args);
462    let outs = trace::bind(
463        p::CUSTOM_VJP_CALL,
464        &inputs,
465        Params::CustomVjp {
466            call: Arc::new(call),
467            fwd: Arc::new(fwd_fn),
468            bwd: Arc::new(tb.function),
469            num_consts,
470        },
471    );
472    out.unflatten_like(&mut outs.into_iter())
473}
474
475pub(crate) fn trace_checkpoint<I: Tree<Trace>, O: Tree<Trace>>(f: &dyn Fn(I) -> O, input: I) -> O {
476    let args = leaves(&input);
477    let mut out: Option<O> = None;
478    let t = trace_function(&avals(&args), |refs| {
479        let o = f(input.unflatten_like(&mut refs.iter().copied()));
480        let l = leaves(&o);
481        out = Some(o);
482        l
483    });
484    let mut inputs = t.captured;
485    inputs.extend(args);
486    let outs = trace::bind(
487        p::CHECKPOINT,
488        &inputs,
489        Params::Checkpoint {
490            body: Arc::new(t.function),
491        },
492    );
493    out.expect("the function was called")
494        .unflatten_like(&mut outs.into_iter())
495}
496
497pub(crate) fn trace_while<C: Tree<Trace>>(
498    cond: &dyn Fn(&C) -> Bool<Trace>,
499    body: &dyn Fn(C) -> C,
500    init: C,
501) -> C {
502    let carry = leaves(&init);
503    let in_avals = avals(&carry);
504    let c = trace_function(&in_avals, |args| {
505        vec![cond(&init.unflatten_like(&mut args.iter().copied())).0]
506    });
507    let b = trace_function(&in_avals, |args| {
508        leaves(&body(init.unflatten_like(&mut args.iter().copied())))
509    });
510    let (nc, nb) = (c.captured.len(), b.captured.len());
511    let mut inputs = c.captured;
512    inputs.extend(b.captured);
513    inputs.extend(carry);
514    let outs = trace::bind(
515        p::WHILE,
516        &inputs,
517        Params::While {
518            cond: Arc::new(c.function),
519            body: Arc::new(b.function),
520            cond_nconsts: nc,
521            body_nconsts: nb,
522        },
523    );
524    init.unflatten_like(&mut outs.into_iter())
525}
526
527pub(crate) fn trace_scan<C: Tree<Trace>, X: Tree<Trace>, Y: Tree<Trace>>(
528    f: &dyn Fn(C, X) -> (C, Y),
529    init: C,
530    xs: X,
531    length: usize,
532    reverse: bool,
533) -> (C, Y) {
534    let carry = leaves(&init);
535    let x_leaves = leaves(&xs);
536    let mut in_avals = avals(&carry);
537    for &x in &x_leaves {
538        let a = trace::aval(x);
539        assert!(
540            a.shape.first() == Some(&length),
541            "scanned arrays need leading dimension {length}, got {a}"
542        );
543        in_avals.push(AVal::new(a.shape.dims()[1..].to_vec(), a.dtype));
544    }
545    let nc = carry.len();
546    let mut y_template: Option<Y> = None;
547    let t = trace_function(&in_avals, |args| {
548        let c = init.unflatten_like(&mut args[..nc].iter().copied());
549        let x = xs.unflatten_like(&mut args[nc..].iter().copied());
550        let (c, y) = f(c, x);
551        let mut out = leaves(&c);
552        out.extend(leaves(&y));
553        y_template = Some(y);
554        out
555    });
556    let num_consts = t.captured.len();
557    let mut inputs = t.captured;
558    inputs.extend(carry);
559    inputs.extend(x_leaves);
560    let outs = trace::bind(
561        p::SCAN,
562        &inputs,
563        Params::Scan {
564            body: Arc::new(t.function),
565            length,
566            reverse,
567            num_consts,
568            num_carry: nc,
569        },
570    );
571    let mut it = outs.into_iter();
572    let c = init.unflatten_like(&mut it);
573    let y = y_template
574        .expect("the body was traced")
575        .unflatten_like(&mut it);
576    (c, y)
577}
578
579pub(crate) fn trace_fori_loop<C: Tree<Trace>>(
580    lo: I32<Trace>,
581    hi: I32<Trace>,
582    body: &dyn Fn(I32<Trace>, C) -> C,
583    init: C,
584) -> C {
585    let static_bound = |b: I32<Trace>| {
586        trace::literal_value(b.0).map(|v| v.as_slice::<i32>().expect("i32 bound")[0])
587    };
588    if let (Some(lo_v), Some(hi_v)) = (static_bound(lo), static_bound(hi)) {
589        let length = usize::try_from(i64::from(hi_v) - i64::from(lo_v)).unwrap_or(0);
590        let ((_, c), ()) = trace_scan(
591            &|(i, c): (I32<Trace>, C), (): ()| ((i + 1, body(i, c)), ()),
592            (lo, init),
593            (),
594            length,
595            false,
596        );
597        return c;
598    }
599    let (_, _, c) = trace_while(
600        &|(i, hi, _): &(I32<Trace>, I32<Trace>, C)| i.lt(*hi),
601        &|(i, hi, c)| (i + 1, hi, body(i, c)),
602        (lo, hi, init),
603    );
604    c
605}