1use 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
15pub 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
25pub 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
47pub 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
71pub 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
96pub 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
108pub 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
121pub 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 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#[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#[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
263pub 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
297pub 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
326pub 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
332fn 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 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}