1use std::fmt;
11use std::sync::Arc;
12
13use ruxla_ir::{AVal, Function, HostArray, Params};
14use ruxla_pjrt::Buffer;
15
16use crate::backend::{Backend, Native, Trace};
17use crate::runtime::{self, Error};
18use crate::trace::{self, TraceRef, trace_function};
19use crate::tree::{Tree, leaves};
20
21pub fn value_and_grad<F>(f: F) -> ValueAndGrad<F> {
41 ValueAndGrad { f }
42}
43
44pub fn grad<F>(f: F) -> Grad<F> {
57 Grad {
58 inner: ValueAndGrad { f },
59 }
60}
61
62pub struct ValueAndGrad<F> {
64 f: F,
65}
66
67pub struct Grad<F> {
69 inner: ValueAndGrad<F>,
70}
71
72impl<F> fmt::Debug for ValueAndGrad<F> {
73 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
74 f.debug_struct("ValueAndGrad").finish_non_exhaustive()
75 }
76}
77
78impl<F> fmt::Debug for Grad<F> {
79 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
80 f.debug_struct("Grad").finish_non_exhaustive()
81 }
82}
83
84struct Derived<O> {
87 function: Function,
88 args: Vec<HostArray>,
89 out: O,
90}
91
92fn trace2<A, B, O>(
96 f: impl FnOnce(A, B) -> O,
97 a_avals: &[AVal],
98 b_avals: &[AVal],
99 a: impl FnOnce(&mut dyn Iterator<Item = TraceRef>) -> A,
100 b: impl FnOnce(&mut dyn Iterator<Item = TraceRef>) -> B,
101) -> (trace::Traced, O)
102where
103 O: Tree<Trace>,
104{
105 let mut in_avals = a_avals.to_vec();
106 in_avals.extend_from_slice(b_avals);
107 let mut out: Option<O> = None;
108 let t = trace_function(&in_avals, |refs| {
109 let mut it = refs.iter().copied();
110 let x = a(&mut it);
111 let y = b(&mut it);
112 let o = f(x, y);
113 let l = leaves(&o);
114 out = Some(o);
115 l
116 });
117 (t, out.expect("the function was called"))
118}
119
120fn native_avals<T: Tree<Native>>(x: &T) -> Vec<AVal> {
121 leaves(x).iter().map(Native::leaf_aval).collect()
122}
123
124fn trace_avals<T: Tree<Trace>>(x: &T) -> Vec<AVal> {
125 leaves(x).iter().map(|&r| trace::aval(r)).collect()
126}
127
128fn mask(skip: usize, n: usize, total: usize) -> Vec<bool> {
130 (0..total).map(|i| i >= skip && i < skip + n).collect()
131}
132
133fn check_float(avals: &[AVal], what: &str) {
134 for a in avals {
135 assert!(
136 a.dtype.is_inexact(),
137 "{what}: differentiated values must be floats or complex numbers, got {a}"
138 );
139 }
140}
141
142fn interpret(f: &Function, args: &[HostArray]) -> Vec<HostArray> {
144 ruxla_interp::eval(f, args).unwrap_or_else(|e| panic!("{e}"))
145}
146
147fn execute_xla(f: &Function, args: &[HostArray]) -> Result<Vec<HostArray>, Error> {
149 let platform = runtime::platform();
150 let client = runtime::client(platform)?;
151 let exe = runtime::compile(platform, f)?;
152 let buffers = args
153 .iter()
154 .map(|a| client.buffer_from_host_array(a))
155 .collect::<Result<Vec<_>, _>>()?;
156 let outs = exe.execute(&buffers.iter().collect::<Vec<_>>())?;
157 Ok(outs
158 .iter()
159 .map(Buffer::to_host_array)
160 .collect::<Result<Vec<_>, _>>()?)
161}
162
163fn bind_function(name: &str, f: Function, inputs: &[TraceRef]) -> Vec<TraceRef> {
165 trace::bind(
166 ruxla_prims::JIT,
167 inputs,
168 Params::Jit {
169 name: String::from(name),
170 body: Arc::new(f),
171 },
172 )
173}
174
175impl<F> ValueAndGrad<F> {
176 fn derive<P, A, O>(&self, params: &P, args: &A) -> Derived<O>
177 where
178 P: Tree<Native>,
179 A: Tree<Native>,
180 O: Tree<Trace>,
181 F: Fn(P::On<Trace>, A::On<Trace>) -> O,
182 {
183 let (pa, aa) = (native_avals(params), native_avals(args));
184 check_float(&pa, "grad");
185 let (t, out) = trace2(
186 &self.f,
187 &pa,
188 &aa,
189 |it| params.rebuild::<Trace>(it),
190 |it| args.rebuild::<Trace>(it),
191 );
192 assert!(
193 t.captured.is_empty(),
194 "a program traced at the top level cannot use values of another trace"
195 );
196 let wrt = mask(0, pa.len(), pa.len() + aa.len());
197 let function = ruxla_transforms::value_and_grad(&t.function, &wrt)
198 .unwrap_or_else(|e| panic!("grad: {e}"));
199 let mut all = leaves(params);
200 all.extend(leaves(args));
201 Derived {
202 function,
203 args: all,
204 out,
205 }
206 }
207
208 fn split<P, O>(d: &Derived<O>, params: &P, outs: Vec<HostArray>) -> (O::On<Native>, P)
209 where
210 P: Tree<Native>,
211 O: Tree<Trace>,
212 {
213 let mut it = outs.into_iter();
214 let value = d.out.rebuild::<Native>(&mut it);
215 (value, params.unflatten_like(&mut it))
216 }
217
218 #[track_caller]
225 pub fn call<P, A, O>(&self, params: &P, args: &A) -> (O::On<Native>, P)
226 where
227 P: Tree<Native>,
228 A: Tree<Native>,
229 O: Tree<Trace>,
230 F: Fn(P::On<Trace>, A::On<Trace>) -> O,
231 {
232 let d = self.derive(params, args);
233 let outs = interpret(&d.function, &d.args);
234 Self::split(&d, params, outs)
235 }
236
237 pub fn call_xla<P, A, O>(&self, params: &P, args: &A) -> Result<(O::On<Native>, P), Error>
248 where
249 P: Tree<Native>,
250 A: Tree<Native>,
251 O: Tree<Trace>,
252 F: Fn(P::On<Trace>, A::On<Trace>) -> O,
253 {
254 let d = self.derive(params, args);
255 let outs = execute_xla(&d.function, &d.args)?;
256 Ok(Self::split(&d, params, outs))
257 }
258
259 pub fn call_traced<P, A, O>(&self, params: P, args: A) -> (O, P)
267 where
268 P: Tree<Trace>,
269 A: Tree<Trace>,
270 O: Tree<Trace>,
271 F: Fn(P, A) -> O,
272 {
273 let (pa, aa) = (trace_avals(¶ms), trace_avals(&args));
274 check_float(&pa, "grad");
275 let (t, out) = trace2(
276 &self.f,
277 &pa,
278 &aa,
279 |it| params.unflatten_like(it),
280 |it| args.unflatten_like(it),
281 );
282 let ncap = t.captured.len();
283 let wrt = mask(ncap, pa.len(), ncap + pa.len() + aa.len());
284 let function = ruxla_transforms::value_and_grad(&t.function, &wrt)
285 .unwrap_or_else(|e| panic!("grad: {e}"));
286 let mut inputs = t.captured;
287 inputs.extend(leaves(¶ms));
288 inputs.extend(leaves(&args));
289 let outs = bind_function("value_and_grad", function, &inputs);
290 let mut it = outs.into_iter();
291 let value = out.unflatten_like(&mut it);
292 (value, params.unflatten_like(&mut it))
293 }
294
295 pub fn make_ir<P, A, O>(&self, params: &P, args: &A) -> Function
302 where
303 P: Tree<Native>,
304 A: Tree<Native>,
305 O: Tree<Trace>,
306 F: Fn(P::On<Trace>, A::On<Trace>) -> O,
307 {
308 self.derive(params, args).function
309 }
310}
311
312impl<F> Grad<F> {
313 #[track_caller]
319 pub fn call<P, A, O>(&self, params: &P, args: &A) -> P
320 where
321 P: Tree<Native>,
322 A: Tree<Native>,
323 O: Tree<Trace>,
324 F: Fn(P::On<Trace>, A::On<Trace>) -> O,
325 {
326 self.inner.call(params, args).1
327 }
328
329 pub fn call_xla<P, A, O>(&self, params: &P, args: &A) -> Result<P, Error>
335 where
336 P: Tree<Native>,
337 A: Tree<Native>,
338 O: Tree<Trace>,
339 F: Fn(P::On<Trace>, A::On<Trace>) -> O,
340 {
341 Ok(self.inner.call_xla(params, args)?.1)
342 }
343
344 pub fn call_traced<P, A, O>(&self, params: P, args: A) -> P
347 where
348 P: Tree<Trace>,
349 A: Tree<Trace>,
350 O: Tree<Trace>,
351 F: Fn(P, A) -> O,
352 {
353 self.inner.call_traced(params, args).1
354 }
355}
356
357pub fn jvp<F>(f: F) -> Jvp<F> {
373 Jvp { f }
374}
375
376pub struct Jvp<F> {
378 f: F,
379}
380
381impl<F> fmt::Debug for Jvp<F> {
382 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
383 f.debug_struct("Jvp").finish_non_exhaustive()
384 }
385}
386
387fn jvp_function(f: &Function, skip: usize) -> Function {
390 let nonzero: Vec<bool> = f
391 .invars
392 .iter()
393 .enumerate()
394 .map(|(i, v)| i >= skip && v.aval().dtype.is_inexact())
395 .collect();
396 let instantiate = vec![true; f.outvars.len()];
397 let (g, out_nonzero) =
398 ruxla_transforms::jvp(f, &nonzero, &instantiate).unwrap_or_else(|e| panic!("jvp: {e}"));
399 let mut g = g;
403 let n_in = f.invars.len();
404 let tangent_vars = g.invars.split_off(n_in);
405 let mut tv = tangent_vars.into_iter();
406 for (i, v) in f.invars.iter().enumerate().skip(skip) {
407 let t = if nonzero[i] {
408 tv.next().expect("a tangent per nonzero input")
409 } else {
410 ruxla_ir::Var::new(v.aval().clone())
411 };
412 g.invars.push(t);
413 }
414 let n_out = f.outvars.len();
415 let tangents = g.outvars.split_off(n_out);
416 let mut to = tangents.into_iter();
417 for (a, nz) in f.outvars.iter().zip(out_nonzero) {
418 let t = if nz {
419 to.next().expect("a tangent per nonzero output")
420 } else {
421 let aval = a.aval();
422 ruxla_ir::Atom::Lit(ruxla_ir::Literal::new(HostArray::zeros(
423 aval.shape.clone(),
424 aval.dtype,
425 )))
426 };
427 g.outvars.push(t);
428 }
429 g
430}
431
432impl<F> Jvp<F> {
433 #[track_caller]
440 pub fn call<I, O>(&self, primals: &I, tangents: &I) -> (O::On<Native>, O::On<Native>)
441 where
442 I: Tree<Native>,
443 O: Tree<Trace>,
444 F: Fn(I::On<Trace>) -> O,
445 {
446 assert_eq!(
447 native_avals(primals),
448 native_avals(tangents),
449 "jvp: the tangents must have the types of the primals"
450 );
451 let (t, out) = crate::transform::trace_with_output(&self.f, primals);
452 let g = jvp_function(&t.function, 0);
453 let mut args = leaves(primals);
454 args.extend(leaves(tangents));
455 let mut it = interpret(&g, &args).into_iter();
456 let o = out.rebuild::<Native>(&mut it);
457 let t = out.rebuild::<Native>(&mut it);
458 (o, t)
459 }
460
461 pub fn call_traced<I, O>(&self, primals: I, tangents: I) -> (O, O)
467 where
468 I: Tree<Trace>,
469 O: Tree<Trace>,
470 F: Fn(I) -> O,
471 {
472 let pa = trace_avals(&primals);
473 assert_eq!(
474 pa,
475 trace_avals(&tangents),
476 "jvp: the tangents must have the types of the primals"
477 );
478 let (t, out) = trace2(
479 |x: I, (): ()| (self.f)(x),
480 &pa,
481 &[],
482 |it| primals.unflatten_like(it),
483 |_| (),
484 );
485 let ncap = t.captured.len();
486 let g = jvp_function(&t.function, ncap);
487 let mut inputs = t.captured;
488 inputs.extend(leaves(&primals));
489 inputs.extend(leaves(&tangents));
490 let outs = bind_function("jvp", g, &inputs);
491 let mut it = outs.into_iter();
492 let o = out.unflatten_like(&mut it);
493 let t = out.unflatten_like(&mut it);
494 (o, t)
495 }
496}
497
498pub fn vjp<F>(f: F) -> VjpFn<F> {
515 VjpFn { f }
516}
517
518pub struct VjpFn<F> {
520 f: F,
521}
522
523impl<F> fmt::Debug for VjpFn<F> {
524 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
525 f.debug_struct("VjpFn").finish_non_exhaustive()
526 }
527}
528
529fn vjp_function(f: &Function, skip: usize) -> Function {
533 use ruxla_ir::{Atom, Eqn, Literal, Var};
534 let wrt: Vec<bool> = f
535 .invars
536 .iter()
537 .enumerate()
538 .map(|(i, v)| i >= skip && v.aval().dtype.is_inexact())
539 .collect();
540 let v = ruxla_transforms::vjp(f, &wrt).unwrap_or_else(|e| panic!("vjp: {e}"));
541 let n_out = f.outvars.len();
542 let invars: Vec<Var> = f
543 .invars
544 .iter()
545 .map(|x| Var::new(x.aval().clone()))
546 .collect();
547 let ct_vars: Vec<Var> = f.outvars.iter().map(|a| Var::new(a.aval())).collect();
548 let fwd_outs: Vec<Var> = v.forward.out_avals().into_iter().map(Var::new).collect();
549 let mut back_inputs: Vec<Atom> = fwd_outs[n_out..].iter().cloned().map(Atom::Var).collect();
550 back_inputs.extend(
551 ct_vars
552 .iter()
553 .zip(&v.differentiable_outputs)
554 .filter(|(_, d)| **d)
555 .map(|(c, _)| Atom::Var(c.clone())),
556 );
557 let back_outs: Vec<Var> = v.backward.out_avals().into_iter().map(Var::new).collect();
558 let call = |body: Function, inputs: Vec<Atom>, outputs: Vec<Var>| Eqn {
559 prim: ruxla_prims::JIT,
560 inputs,
561 params: Params::Jit {
562 name: String::from("vjp"),
563 body: Arc::new(body),
564 },
565 outputs,
566 loc: None,
567 };
568 let eqns = vec![
569 call(
570 v.forward,
571 invars.iter().cloned().map(Atom::Var).collect(),
572 fwd_outs.clone(),
573 ),
574 call(v.backward, back_inputs, back_outs.clone()),
575 ];
576 let mut outvars: Vec<Atom> = fwd_outs[..n_out].iter().cloned().map(Atom::Var).collect();
577 let mut cts = back_outs.into_iter();
578 for (x, &w) in f.invars.iter().zip(&wrt).skip(skip) {
579 outvars.push(if w {
580 Atom::Var(cts.next().expect("a cotangent per input"))
581 } else {
582 let a = x.aval();
583 Atom::Lit(Literal::new(HostArray::zeros(a.shape.clone(), a.dtype)))
584 });
585 }
586 let mut all_invars = invars;
587 all_invars.extend(ct_vars);
588 Function {
589 constvars: Vec::new(),
590 invars: all_invars,
591 eqns,
592 outvars,
593 }
594}
595
596impl<F> VjpFn<F> {
597 #[track_caller]
605 pub fn call<I, O>(&self, primals: &I, cotangents: &O::On<Native>) -> (O::On<Native>, I)
606 where
607 I: Tree<Native>,
608 O: Tree<Trace>,
609 O::On<Native>: Tree<Native>,
610 F: Fn(I::On<Trace>) -> O,
611 {
612 let (t, out) = crate::transform::trace_with_output(&self.f, primals);
613 assert_eq!(
614 t.function.out_avals(),
615 native_avals(cotangents),
616 "vjp: the cotangents must have the types of the outputs"
617 );
618 let g = vjp_function(&t.function, 0);
619 let mut args = leaves(primals);
620 args.extend(leaves(cotangents));
621 let mut it = interpret(&g, &args).into_iter();
622 let o = out.rebuild::<Native>(&mut it);
623 (o, primals.unflatten_like(&mut it))
624 }
625
626 pub fn call_traced<I, O>(&self, primals: I, cotangents: O) -> (O, I)
633 where
634 I: Tree<Trace>,
635 O: Tree<Trace>,
636 F: Fn(I) -> O,
637 {
638 let pa = trace_avals(&primals);
639 let (t, out) = trace2(
640 |x: I, (): ()| (self.f)(x),
641 &pa,
642 &[],
643 |it| primals.unflatten_like(it),
644 |_| (),
645 );
646 assert_eq!(
647 t.function.out_avals()[..],
648 trace_avals(&cotangents)[..],
649 "vjp: the cotangents must have the types of the outputs"
650 );
651 let ncap = t.captured.len();
652 let g = vjp_function(&t.function, ncap);
653 let mut inputs = t.captured;
654 inputs.extend(leaves(&primals));
655 inputs.extend(leaves(&cotangents));
656 let outs = bind_function("vjp", g, &inputs);
657 let mut it = outs.into_iter();
658 let o = out.unflatten_like(&mut it);
659 (o, primals.unflatten_like(&mut it))
660 }
661}