use std::sync::Arc;
use ruxla_ir::{AVal, Params, Var};
use ruxla_kernels::Element;
use ruxla_prims as p;
use crate::backend::{Backend, Trace};
use crate::trace::{self, TraceRef, trace_function};
use crate::tree::{Tree, leaves};
use crate::value::{Array, Bool, I32, Scalar};
pub fn select<B: Backend, T: Element>(
pred: Bool<B>,
on_true: impl Into<Scalar<B, T>>,
on_false: impl Into<Scalar<B, T>>,
) -> Scalar<B, T> {
Scalar(B::select::<T>(pred.0, on_true.into().0, on_false.into().0))
}
pub fn cond<B: Backend, S: Tree<B>, R: Tree<B>>(
pred: Bool<B>,
true_fn: impl Fn(S) -> R,
false_fn: impl Fn(S) -> R,
operand: S,
) -> R {
B::cond(pred.cast::<i32>(), &[&false_fn, &true_fn], operand)
}
pub fn switch<B: Backend, S: Tree<B>, R: Tree<B>>(
index: I32<B>,
branches: &[&dyn Fn(S) -> R],
operand: S,
) -> R {
assert!(!branches.is_empty(), "switch needs at least one branch");
let lo = Array::<B, i32>::from(Scalar::new(0));
let hi = Array::<B, i32>::from(Scalar::new(branches.len() as i32 - 1));
let clamped = Array::<B, i32>(B::a_clamp::<i32>(&lo.0, &index.to_array().0, &hi.0)).to_scalar();
B::cond(clamped, branches, operand)
}
impl<B: Backend, T: Element> From<Scalar<B, T>> for Array<B, T> {
fn from(s: Scalar<B, T>) -> Self {
s.to_array()
}
}
pub fn while_loop<B: Backend, C: Tree<B>>(
cond_fn: impl Fn(&C) -> Bool<B>,
body_fn: impl Fn(C) -> C,
init: C,
) -> C {
B::while_loop(&cond_fn, &body_fn, init)
}
pub fn fori_loop<B: Backend, C: Tree<B>>(
lo: impl Into<I32<B>>,
hi: impl Into<I32<B>>,
body: impl Fn(I32<B>, C) -> C,
init: C,
) -> C {
B::fori_loop(lo.into(), hi.into(), &body, init)
}
pub fn scan<B: Backend, C: Tree<B>, X: Tree<B>, Y: Tree<B>>(
f: impl Fn(C, X) -> (C, Y),
init: C,
xs: X,
length: usize,
) -> (C, Y) {
B::scan(&f, init, xs, length, false)
}
pub fn scan_reverse<B: Backend, C: Tree<B>, X: Tree<B>, Y: Tree<B>>(
f: impl Fn(C, X) -> (C, Y),
init: C,
xs: X,
length: usize,
) -> (C, Y) {
B::scan(&f, init, xs, length, true)
}
fn avals(refs: &[TraceRef]) -> Vec<AVal> {
refs.iter().map(|&r| trace::aval(r)).collect()
}
pub(crate) fn trace_cond<S: Tree<Trace>, R: Tree<Trace>>(
index: I32<Trace>,
branches: &[&dyn Fn(S) -> R],
operand: S,
) -> R {
let ops = leaves(&operand);
let in_avals = avals(&ops);
let mut out_template: Option<R> = None;
let traced: Vec<_> = branches
.iter()
.map(|b| {
trace_function(&in_avals, |args| {
let op = operand.unflatten_like(&mut args.iter().copied());
let r = b(op);
let l = leaves(&r);
out_template = Some(r);
l
})
})
.collect();
let consts: Vec<TraceRef> = traced
.iter()
.flat_map(|t| t.captured.iter().copied())
.collect();
let functions: Vec<Arc<ruxla_ir::Function>> = traced
.iter()
.enumerate()
.map(|(k, t)| {
let n = t.captured.len();
let mut f = t.function.clone();
let own = f.invars.drain(..n).collect::<Vec<Var>>();
let mut invars = Vec::new();
for (j, u) in traced.iter().enumerate() {
if j == k {
invars.extend(own.iter().cloned());
} else {
invars.extend(u.captured.iter().map(|&r| Var::new(trace::aval(r))));
}
}
invars.append(&mut f.invars);
f.invars = invars;
Arc::new(f)
})
.collect();
let mut inputs = vec![index.0];
inputs.extend(consts);
inputs.extend(ops);
let outs = trace::bind(
p::COND,
&inputs,
Params::Cond {
branches: functions,
},
);
out_template
.expect("at least one branch")
.unflatten_like(&mut outs.into_iter())
}
#[inline]
pub fn select_with<B: Backend, T: Tree<B>>(
pred: Bool<B>,
on_true: impl FnOnce() -> T,
on_false: impl FnOnce() -> T,
) -> T {
if let Some(p) = B::branch_value(pred) {
if p { on_true() } else { on_false() }
} else {
crate::tree::select_tree(pred, &on_true(), &on_false())
}
}
#[inline]
pub fn select_with_operand<B: Backend, S: Clone, T: Tree<B>>(
pred: Bool<B>,
operand: S,
on_true: impl FnOnce(S) -> T,
on_false: impl FnOnce(S) -> T,
) -> T {
if let Some(p) = B::branch_value(pred) {
if p {
on_true(operand)
} else {
on_false(operand)
}
} else {
crate::tree::select_tree(pred, &on_true(operand.clone()), &on_false(operand))
}
}
pub fn custom_jvp<B: Backend, I: Tree<B>, O: Tree<B>>(
f: impl Fn(I) -> O,
jvp: impl Fn(I, I) -> (O, O),
primals: I,
) -> O {
B::custom_jvp(&f, &jvp, primals)
}
pub fn custom_vjp<B: Backend, I: Tree<B>, O: Tree<B>, R: Tree<B>>(
f: impl Fn(I) -> O,
fwd: impl Fn(I) -> (O, R),
bwd: impl Fn(R, O) -> I,
primals: I,
) -> O {
B::custom_vjp(&f, &fwd, &bwd, primals)
}
pub fn checkpoint<B: Backend, I: Tree<B>, O: Tree<B>>(f: impl Fn(I) -> O, input: I) -> O {
B::checkpoint(&f, input)
}
fn share_captured(traced: &[&trace::Traced]) -> (Vec<TraceRef>, Vec<ruxla_ir::Function>) {
let consts: Vec<TraceRef> = traced
.iter()
.flat_map(|t| t.captured.iter().copied())
.collect();
let functions = traced
.iter()
.enumerate()
.map(|(k, t)| {
let mut f = t.function.clone();
let own: Vec<Var> = f.invars.drain(..t.captured.len()).collect();
let mut invars = Vec::new();
for (j, u) in traced.iter().enumerate() {
if j == k {
invars.extend(own.iter().cloned());
} else {
invars.extend(u.captured.iter().map(|&r| Var::new(trace::aval(r))));
}
}
invars.append(&mut f.invars);
f.invars = invars;
f
})
.collect();
(consts, functions)
}
pub(crate) fn trace_custom_jvp<I: Tree<Trace>, O: Tree<Trace>>(
f: &dyn Fn(I) -> O,
jvp: &dyn Fn(I, I) -> (O, O),
primals: I,
) -> O {
let args = leaves(&primals);
let in_avals = avals(&args);
let mut out: Option<O> = None;
let tf = trace_function(&in_avals, |refs| {
let o = f(primals.unflatten_like(&mut refs.iter().copied()));
let l = leaves(&o);
out = Some(o);
l
});
let mut jvp_avals = in_avals.clone();
jvp_avals.extend(in_avals.iter().cloned());
let tj = trace_function(&jvp_avals, |refs| {
let mut it = refs.iter().copied();
let x = primals.unflatten_like(&mut it);
let t = primals.unflatten_like(&mut it);
let (o, to) = jvp(x, t);
let mut l = leaves(&o);
l.extend(leaves(&to));
l
});
let (consts, mut fs) = share_captured(&[&tf, &tj]);
let jvp_fn = fs.pop().expect("two functions");
let call = fs.pop().expect("two functions");
assert_eq!(
jvp_fn.out_avals()[..call.outvars.len()],
call.out_avals()[..],
"custom_jvp: the rule must return outputs of the types of the function's"
);
let num_consts = consts.len();
let mut inputs = consts;
inputs.extend(args);
let outs = trace::bind(
p::CUSTOM_JVP_CALL,
&inputs,
Params::CustomJvp {
call: Arc::new(call),
jvp: Arc::new(jvp_fn),
num_consts,
},
);
out.expect("the function was called")
.unflatten_like(&mut outs.into_iter())
}
pub(crate) fn trace_custom_vjp<I: Tree<Trace>, O: Tree<Trace>, R: Tree<Trace>>(
f: &dyn Fn(I) -> O,
fwd: &dyn Fn(I) -> (O, R),
bwd: &dyn Fn(R, O) -> I,
primals: I,
) -> O {
let args = leaves(&primals);
let in_avals = avals(&args);
let mut out: Option<O> = None;
let tf = trace_function(&in_avals, |refs| {
let o = f(primals.unflatten_like(&mut refs.iter().copied()));
let l = leaves(&o);
out = Some(o);
l
});
let out = out.expect("the function was called");
let mut residuals: Option<R> = None;
let tw = trace_function(&in_avals, |refs| {
let (o, r) = fwd(primals.unflatten_like(&mut refs.iter().copied()));
let mut l = leaves(&o);
l.extend(leaves(&r));
residuals = Some(r);
l
});
let residuals = residuals.expect("the function was called");
let n_out = tf.function.outvars.len();
let mut bwd_avals = tw.function.out_avals()[n_out..].to_vec();
bwd_avals.extend(tf.function.out_avals());
let tb = trace_function(&bwd_avals, |refs| {
let mut it = refs.iter().copied();
let r = residuals.unflatten_like(&mut it);
let g = out.unflatten_like(&mut it);
leaves(&bwd(r, g))
});
assert!(
tb.captured.is_empty(),
"custom_vjp: bwd must not capture traced values; return them as residuals from fwd"
);
assert_eq!(
tb.function.out_avals(),
in_avals,
"custom_vjp: bwd must return cotangents of the types of the primals"
);
let (consts, mut fs) = share_captured(&[&tf, &tw]);
let fwd_fn = fs.pop().expect("two functions");
let call = fs.pop().expect("two functions");
let num_consts = consts.len();
let mut inputs = consts;
inputs.extend(args);
let outs = trace::bind(
p::CUSTOM_VJP_CALL,
&inputs,
Params::CustomVjp {
call: Arc::new(call),
fwd: Arc::new(fwd_fn),
bwd: Arc::new(tb.function),
num_consts,
},
);
out.unflatten_like(&mut outs.into_iter())
}
pub(crate) fn trace_checkpoint<I: Tree<Trace>, O: Tree<Trace>>(f: &dyn Fn(I) -> O, input: I) -> O {
let args = leaves(&input);
let mut out: Option<O> = None;
let t = trace_function(&avals(&args), |refs| {
let o = f(input.unflatten_like(&mut refs.iter().copied()));
let l = leaves(&o);
out = Some(o);
l
});
let mut inputs = t.captured;
inputs.extend(args);
let outs = trace::bind(
p::CHECKPOINT,
&inputs,
Params::Checkpoint {
body: Arc::new(t.function),
},
);
out.expect("the function was called")
.unflatten_like(&mut outs.into_iter())
}
pub(crate) fn trace_while<C: Tree<Trace>>(
cond: &dyn Fn(&C) -> Bool<Trace>,
body: &dyn Fn(C) -> C,
init: C,
) -> C {
let carry = leaves(&init);
let in_avals = avals(&carry);
let c = trace_function(&in_avals, |args| {
vec![cond(&init.unflatten_like(&mut args.iter().copied())).0]
});
let b = trace_function(&in_avals, |args| {
leaves(&body(init.unflatten_like(&mut args.iter().copied())))
});
let (nc, nb) = (c.captured.len(), b.captured.len());
let mut inputs = c.captured;
inputs.extend(b.captured);
inputs.extend(carry);
let outs = trace::bind(
p::WHILE,
&inputs,
Params::While {
cond: Arc::new(c.function),
body: Arc::new(b.function),
cond_nconsts: nc,
body_nconsts: nb,
},
);
init.unflatten_like(&mut outs.into_iter())
}
pub(crate) fn trace_scan<C: Tree<Trace>, X: Tree<Trace>, Y: Tree<Trace>>(
f: &dyn Fn(C, X) -> (C, Y),
init: C,
xs: X,
length: usize,
reverse: bool,
) -> (C, Y) {
let carry = leaves(&init);
let x_leaves = leaves(&xs);
let mut in_avals = avals(&carry);
for &x in &x_leaves {
let a = trace::aval(x);
assert!(
a.shape.first() == Some(&length),
"scanned arrays need leading dimension {length}, got {a}"
);
in_avals.push(AVal::new(a.shape.dims()[1..].to_vec(), a.dtype));
}
let nc = carry.len();
let mut y_template: Option<Y> = None;
let t = trace_function(&in_avals, |args| {
let c = init.unflatten_like(&mut args[..nc].iter().copied());
let x = xs.unflatten_like(&mut args[nc..].iter().copied());
let (c, y) = f(c, x);
let mut out = leaves(&c);
out.extend(leaves(&y));
y_template = Some(y);
out
});
let num_consts = t.captured.len();
let mut inputs = t.captured;
inputs.extend(carry);
inputs.extend(x_leaves);
let outs = trace::bind(
p::SCAN,
&inputs,
Params::Scan {
body: Arc::new(t.function),
length,
reverse,
num_consts,
num_carry: nc,
},
);
let mut it = outs.into_iter();
let c = init.unflatten_like(&mut it);
let y = y_template
.expect("the body was traced")
.unflatten_like(&mut it);
(c, y)
}
pub(crate) fn trace_fori_loop<C: Tree<Trace>>(
lo: I32<Trace>,
hi: I32<Trace>,
body: &dyn Fn(I32<Trace>, C) -> C,
init: C,
) -> C {
let static_bound = |b: I32<Trace>| {
trace::literal_value(b.0).map(|v| v.as_slice::<i32>().expect("i32 bound")[0])
};
if let (Some(lo_v), Some(hi_v)) = (static_bound(lo), static_bound(hi)) {
let length = usize::try_from(i64::from(hi_v) - i64::from(lo_v)).unwrap_or(0);
let ((_, c), ()) = trace_scan(
&|(i, c): (I32<Trace>, C), (): ()| ((i + 1, body(i, c)), ()),
(lo, init),
(),
length,
false,
);
return c;
}
let (_, _, c) = trace_while(
&|(i, hi, _): &(I32<Trace>, I32<Trace>, C)| i.lt(*hi),
&|(i, hi, c)| (i + 1, hi, body(i, c)),
(lo, hi, init),
);
c
}