ruxla-core 0.1.0

Internal crate of ruxla (use the `ruxla` crate): the frontend of ruxla (backend-generic values, native and tracing backends)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
//! Automatic differentiation: `grad`, `value_and_grad`, `jvp`, and `vjp`.
//!
//! The functions take and return pytrees of [`Trace`] values; they are
//! traced, differentiated by `ruxla-transforms` (JAX's rules), and run with
//! the interpreter (`call`), with XLA (`call_xla`), or inside another trace
//! (`call_traced`, which adds the derivative to the outer IR as a `jit`
//! equation, so that `jit(|..| grad(f).call_traced(..))` compiles the whole
//! training step).

use std::fmt;
use std::sync::Arc;

use ruxla_ir::{AVal, Function, HostArray, Params};
use ruxla_pjrt::Buffer;

use crate::backend::{Backend, Native, Trace};
use crate::runtime::{self, Error};
use crate::trace::{self, TraceRef, trace_function};
use crate::tree::{Tree, leaves};

/// Returns a function that computes `f(params, args)` and its gradient with
/// respect to `params`, like `jax.value_and_grad(f, has_aux=True)`.
///
/// `f` takes the parameters (a pytree of float values, which are
/// differentiated) and other arguments (which are not), and returns a
/// pytree whose first leaf is the loss, a float scalar. The other leaves are
/// auxiliary values, returned as they are. The gradient has the structure of
/// the parameters.
///
/// # Examples
///
/// ```
/// use ruxla_core::{F32, Trace, value_and_grad};
///
/// // d/dx (x * x * y) = 2 * x * y
/// let f = value_and_grad(|x: F32<Trace>, y: F32<Trace>| x * x * y);
/// let (value, grad) = f.call(&F32::new(3.0), &F32::new(2.0));
/// assert_eq!((value.value(), grad.value()), (18.0, 12.0));
/// ```
pub fn value_and_grad<F>(f: F) -> ValueAndGrad<F> {
    ValueAndGrad { f }
}

/// Returns a function that computes the gradient of `f(params, args)` with
/// respect to `params`, like `jax.grad`. See [`value_and_grad`] for what `f`
/// takes and returns (auxiliary outputs are dropped).
///
/// # Examples
///
/// ```
/// use ruxla_core::{F32, Trace, grad};
///
/// let g = grad(|x: F32<Trace>, (): ()| x.sin());
/// assert_eq!(g.call(&F32::new(0.0), &()).value(), 1.0);
/// ```
pub fn grad<F>(f: F) -> Grad<F> {
    Grad {
        inner: ValueAndGrad { f },
    }
}

/// See [`value_and_grad`].
pub struct ValueAndGrad<F> {
    f: F,
}

/// See [`grad`].
pub struct Grad<F> {
    inner: ValueAndGrad<F>,
}

impl<F> fmt::Debug for ValueAndGrad<F> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ValueAndGrad").finish_non_exhaustive()
    }
}

impl<F> fmt::Debug for Grad<F> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Grad").finish_non_exhaustive()
    }
}

/// A derivative traced for some inputs: the IR, the leaves of its inputs,
/// and the output of tracing (for the structure of the results).
struct Derived<O> {
    function: Function,
    args: Vec<HostArray>,
    out: O,
}

/// Traces `f(a, b)` on values shaped like `a` and `b`; the IR takes the
/// values captured from outer traces (none at the top level), then the
/// leaves of `a`, then those of `b`.
fn trace2<A, B, O>(
    f: impl FnOnce(A, B) -> O,
    a_avals: &[AVal],
    b_avals: &[AVal],
    a: impl FnOnce(&mut dyn Iterator<Item = TraceRef>) -> A,
    b: impl FnOnce(&mut dyn Iterator<Item = TraceRef>) -> B,
) -> (trace::Traced, O)
where
    O: Tree<Trace>,
{
    let mut in_avals = a_avals.to_vec();
    in_avals.extend_from_slice(b_avals);
    let mut out: Option<O> = None;
    let t = trace_function(&in_avals, |refs| {
        let mut it = refs.iter().copied();
        let x = a(&mut it);
        let y = b(&mut it);
        let o = f(x, y);
        let l = leaves(&o);
        out = Some(o);
        l
    });
    (t, out.expect("the function was called"))
}

fn native_avals<T: Tree<Native>>(x: &T) -> Vec<AVal> {
    leaves(x).iter().map(Native::leaf_aval).collect()
}

fn trace_avals<T: Tree<Trace>>(x: &T) -> Vec<AVal> {
    leaves(x).iter().map(|&r| trace::aval(r)).collect()
}

/// The mask of the inputs differentiated: `n` after `skip`, of `total`.
fn mask(skip: usize, n: usize, total: usize) -> Vec<bool> {
    (0..total).map(|i| i >= skip && i < skip + n).collect()
}

fn check_float(avals: &[AVal], what: &str) {
    for a in avals {
        assert!(
            a.dtype.is_inexact(),
            "{what}: differentiated values must be floats or complex numbers, got {a}"
        );
    }
}

/// Runs `f` with the interpreter.
fn interpret(f: &Function, args: &[HostArray]) -> Vec<HostArray> {
    ruxla_interp::eval(f, args).unwrap_or_else(|e| panic!("{e}"))
}

/// Runs `f` with XLA.
fn execute_xla(f: &Function, args: &[HostArray]) -> Result<Vec<HostArray>, Error> {
    let platform = runtime::platform();
    let client = runtime::client(platform)?;
    let exe = runtime::compile(platform, f)?;
    let buffers = args
        .iter()
        .map(|a| client.buffer_from_host_array(a))
        .collect::<Result<Vec<_>, _>>()?;
    let outs = exe.execute(&buffers.iter().collect::<Vec<_>>())?;
    Ok(outs
        .iter()
        .map(Buffer::to_host_array)
        .collect::<Result<Vec<_>, _>>()?)
}

/// Adds `f` applied to `inputs` to the current trace as a `jit` equation.
fn bind_function(name: &str, f: Function, inputs: &[TraceRef]) -> Vec<TraceRef> {
    trace::bind(
        ruxla_prims::JIT,
        inputs,
        Params::Jit {
            name: String::from(name),
            body: Arc::new(f),
        },
    )
}

impl<F> ValueAndGrad<F> {
    fn derive<P, A, O>(&self, params: &P, args: &A) -> Derived<O>
    where
        P: Tree<Native>,
        A: Tree<Native>,
        O: Tree<Trace>,
        F: Fn(P::On<Trace>, A::On<Trace>) -> O,
    {
        let (pa, aa) = (native_avals(params), native_avals(args));
        check_float(&pa, "grad");
        let (t, out) = trace2(
            &self.f,
            &pa,
            &aa,
            |it| params.rebuild::<Trace>(it),
            |it| args.rebuild::<Trace>(it),
        );
        assert!(
            t.captured.is_empty(),
            "a program traced at the top level cannot use values of another trace"
        );
        let wrt = mask(0, pa.len(), pa.len() + aa.len());
        let function = ruxla_transforms::value_and_grad(&t.function, &wrt)
            .unwrap_or_else(|e| panic!("grad: {e}"));
        let mut all = leaves(params);
        all.extend(leaves(args));
        Derived {
            function,
            args: all,
            out,
        }
    }

    fn split<P, O>(d: &Derived<O>, params: &P, outs: Vec<HostArray>) -> (O::On<Native>, P)
    where
        P: Tree<Native>,
        O: Tree<Trace>,
    {
        let mut it = outs.into_iter();
        let value = d.out.rebuild::<Native>(&mut it);
        (value, params.unflatten_like(&mut it))
    }

    /// Computes the value and the gradient with the interpreter.
    ///
    /// # Panics
    ///
    /// Panics if a parameter is not a float, if the first output is not a
    /// float scalar, or if a primitive has no differentiation rule.
    #[track_caller]
    pub fn call<P, A, O>(&self, params: &P, args: &A) -> (O::On<Native>, P)
    where
        P: Tree<Native>,
        A: Tree<Native>,
        O: Tree<Trace>,
        F: Fn(P::On<Trace>, A::On<Trace>) -> O,
    {
        let d = self.derive(params, args);
        let outs = interpret(&d.function, &d.args);
        Self::split(&d, params, outs)
    }

    /// Computes the value and the gradient with XLA.
    ///
    /// # Errors
    ///
    /// Returns an error if no PJRT plugin is configured, or if compiling or
    /// running fails.
    ///
    /// # Panics
    ///
    /// See [`ValueAndGrad::call`].
    pub fn call_xla<P, A, O>(&self, params: &P, args: &A) -> Result<(O::On<Native>, P), Error>
    where
        P: Tree<Native>,
        A: Tree<Native>,
        O: Tree<Trace>,
        F: Fn(P::On<Trace>, A::On<Trace>) -> O,
    {
        let d = self.derive(params, args);
        let outs = execute_xla(&d.function, &d.args)?;
        Ok(Self::split(&d, params, outs))
    }

    /// Computes the value and the gradient inside another trace: the
    /// derivative becomes a `jit` equation of the outer IR. Values that `f`
    /// captures from the outer trace are not differentiated.
    ///
    /// # Panics
    ///
    /// See [`ValueAndGrad::call`].
    pub fn call_traced<P, A, O>(&self, params: P, args: A) -> (O, P)
    where
        P: Tree<Trace>,
        A: Tree<Trace>,
        O: Tree<Trace>,
        F: Fn(P, A) -> O,
    {
        let (pa, aa) = (trace_avals(&params), trace_avals(&args));
        check_float(&pa, "grad");
        let (t, out) = trace2(
            &self.f,
            &pa,
            &aa,
            |it| params.unflatten_like(it),
            |it| args.unflatten_like(it),
        );
        let ncap = t.captured.len();
        let wrt = mask(ncap, pa.len(), ncap + pa.len() + aa.len());
        let function = ruxla_transforms::value_and_grad(&t.function, &wrt)
            .unwrap_or_else(|e| panic!("grad: {e}"));
        let mut inputs = t.captured;
        inputs.extend(leaves(&params));
        inputs.extend(leaves(&args));
        let outs = bind_function("value_and_grad", function, &inputs);
        let mut it = outs.into_iter();
        let value = out.unflatten_like(&mut it);
        (value, params.unflatten_like(&mut it))
    }

    /// Returns the IR of the derivative for inputs shaped like `params` and
    /// `args`: the outputs of `f`, then the gradient.
    ///
    /// # Panics
    ///
    /// See [`ValueAndGrad::call`].
    pub fn make_ir<P, A, O>(&self, params: &P, args: &A) -> Function
    where
        P: Tree<Native>,
        A: Tree<Native>,
        O: Tree<Trace>,
        F: Fn(P::On<Trace>, A::On<Trace>) -> O,
    {
        self.derive(params, args).function
    }
}

impl<F> Grad<F> {
    /// Computes the gradient with the interpreter.
    ///
    /// # Panics
    ///
    /// See [`ValueAndGrad::call`].
    #[track_caller]
    pub fn call<P, A, O>(&self, params: &P, args: &A) -> P
    where
        P: Tree<Native>,
        A: Tree<Native>,
        O: Tree<Trace>,
        F: Fn(P::On<Trace>, A::On<Trace>) -> O,
    {
        self.inner.call(params, args).1
    }

    /// Computes the gradient with XLA.
    ///
    /// # Errors
    ///
    /// See [`ValueAndGrad::call_xla`].
    pub fn call_xla<P, A, O>(&self, params: &P, args: &A) -> Result<P, Error>
    where
        P: Tree<Native>,
        A: Tree<Native>,
        O: Tree<Trace>,
        F: Fn(P::On<Trace>, A::On<Trace>) -> O,
    {
        Ok(self.inner.call_xla(params, args)?.1)
    }

    /// Computes the gradient inside another trace; see
    /// [`ValueAndGrad::call_traced`].
    pub fn call_traced<P, A, O>(&self, params: P, args: A) -> P
    where
        P: Tree<Trace>,
        A: Tree<Trace>,
        O: Tree<Trace>,
        F: Fn(P, A) -> O,
    {
        self.inner.call_traced(params, args).1
    }
}

/// Returns a function that computes `f(primals)` and its derivative in the
/// direction of `tangents` (forward mode), like `jax.jvp`.
///
/// Tangents of non-float inputs are ignored; tangents of non-float outputs
/// are zeros.
///
/// # Examples
///
/// ```
/// use ruxla_core::{F32, Trace, jvp};
///
/// let f = jvp(|(x, y): (F32<Trace>, F32<Trace>)| x * y);
/// let (out, t) = f.call(&(F32::new(3.0), F32::new(2.0)), &(F32::new(1.0), F32::new(0.0)));
/// assert_eq!((out.value(), t.value()), (6.0, 2.0));
/// ```
pub fn jvp<F>(f: F) -> Jvp<F> {
    Jvp { f }
}

/// See [`jvp`].
pub struct Jvp<F> {
    f: F,
}

impl<F> fmt::Debug for Jvp<F> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Jvp").finish_non_exhaustive()
    }
}

/// The JVP of a traced function with every float input and output
/// differentiated, with zeros for the tangents of non-float outputs.
fn jvp_function(f: &Function, skip: usize) -> Function {
    let nonzero: Vec<bool> = f
        .invars
        .iter()
        .enumerate()
        .map(|(i, v)| i >= skip && v.aval().dtype.is_inexact())
        .collect();
    let instantiate = vec![true; f.outvars.len()];
    let (g, out_nonzero) =
        ruxla_transforms::jvp(f, &nonzero, &instantiate).unwrap_or_else(|e| panic!("jvp: {e}"));
    // Inputs: all primals, then a tangent for every input after `skip` (the
    // non-float ones unused); outputs: primals, then a tangent for every
    // output (zeros for the non-float ones).
    let mut g = g;
    let n_in = f.invars.len();
    let tangent_vars = g.invars.split_off(n_in);
    let mut tv = tangent_vars.into_iter();
    for (i, v) in f.invars.iter().enumerate().skip(skip) {
        let t = if nonzero[i] {
            tv.next().expect("a tangent per nonzero input")
        } else {
            ruxla_ir::Var::new(v.aval().clone())
        };
        g.invars.push(t);
    }
    let n_out = f.outvars.len();
    let tangents = g.outvars.split_off(n_out);
    let mut to = tangents.into_iter();
    for (a, nz) in f.outvars.iter().zip(out_nonzero) {
        let t = if nz {
            to.next().expect("a tangent per nonzero output")
        } else {
            let aval = a.aval();
            ruxla_ir::Atom::Lit(ruxla_ir::Literal::new(HostArray::zeros(
                aval.shape.clone(),
                aval.dtype,
            )))
        };
        g.outvars.push(t);
    }
    g
}

impl<F> Jvp<F> {
    /// Computes the outputs and their tangents with the interpreter.
    ///
    /// # Panics
    ///
    /// Panics if the primals and tangents differ in structure or types, or
    /// if a primitive has no JVP rule.
    #[track_caller]
    pub fn call<I, O>(&self, primals: &I, tangents: &I) -> (O::On<Native>, O::On<Native>)
    where
        I: Tree<Native>,
        O: Tree<Trace>,
        F: Fn(I::On<Trace>) -> O,
    {
        assert_eq!(
            native_avals(primals),
            native_avals(tangents),
            "jvp: the tangents must have the types of the primals"
        );
        let (t, out) = crate::transform::trace_with_output(&self.f, primals);
        let g = jvp_function(&t.function, 0);
        let mut args = leaves(primals);
        args.extend(leaves(tangents));
        let mut it = interpret(&g, &args).into_iter();
        let o = out.rebuild::<Native>(&mut it);
        let t = out.rebuild::<Native>(&mut it);
        (o, t)
    }

    /// Computes the outputs and their tangents inside another trace.
    ///
    /// # Panics
    ///
    /// See [`Jvp::call`].
    pub fn call_traced<I, O>(&self, primals: I, tangents: I) -> (O, O)
    where
        I: Tree<Trace>,
        O: Tree<Trace>,
        F: Fn(I) -> O,
    {
        let pa = trace_avals(&primals);
        assert_eq!(
            pa,
            trace_avals(&tangents),
            "jvp: the tangents must have the types of the primals"
        );
        let (t, out) = trace2(
            |x: I, (): ()| (self.f)(x),
            &pa,
            &[],
            |it| primals.unflatten_like(it),
            |_| (),
        );
        let ncap = t.captured.len();
        let g = jvp_function(&t.function, ncap);
        let mut inputs = t.captured;
        inputs.extend(leaves(&primals));
        inputs.extend(leaves(&tangents));
        let outs = bind_function("jvp", g, &inputs);
        let mut it = outs.into_iter();
        let o = out.unflatten_like(&mut it);
        let t = out.unflatten_like(&mut it);
        (o, t)
    }
}

/// Returns a function that computes `f(primals)` and the cotangents of the
/// inputs for given cotangents of the outputs (reverse mode), like calling
/// the function that `jax.vjp` returns.
///
/// Cotangents of non-float outputs are ignored; cotangents of non-float
/// inputs are zeros.
///
/// # Examples
///
/// ```
/// use ruxla_core::{F32, Trace, vjp};
///
/// let f = vjp(|(x, y): (F32<Trace>, F32<Trace>)| x * y);
/// let (out, (cx, cy)) = f.call(&(F32::new(3.0), F32::new(2.0)), &F32::new(1.0));
/// assert_eq!((out.value(), cx.value(), cy.value()), (6.0, 2.0, 3.0));
/// ```
pub fn vjp<F>(f: F) -> VjpFn<F> {
    VjpFn { f }
}

/// See [`vjp`].
pub struct VjpFn<F> {
    f: F,
}

impl<F> fmt::Debug for VjpFn<F> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("VjpFn").finish_non_exhaustive()
    }
}

/// A function of the inputs of `f` (after `skip` captured values) and a
/// cotangent for every output, returning the outputs, then a cotangent for
/// every input after `skip` (zeros for non-floats).
fn vjp_function(f: &Function, skip: usize) -> Function {
    use ruxla_ir::{Atom, Eqn, Literal, Var};
    let wrt: Vec<bool> = f
        .invars
        .iter()
        .enumerate()
        .map(|(i, v)| i >= skip && v.aval().dtype.is_inexact())
        .collect();
    let v = ruxla_transforms::vjp(f, &wrt).unwrap_or_else(|e| panic!("vjp: {e}"));
    let n_out = f.outvars.len();
    let invars: Vec<Var> = f
        .invars
        .iter()
        .map(|x| Var::new(x.aval().clone()))
        .collect();
    let ct_vars: Vec<Var> = f.outvars.iter().map(|a| Var::new(a.aval())).collect();
    let fwd_outs: Vec<Var> = v.forward.out_avals().into_iter().map(Var::new).collect();
    let mut back_inputs: Vec<Atom> = fwd_outs[n_out..].iter().cloned().map(Atom::Var).collect();
    back_inputs.extend(
        ct_vars
            .iter()
            .zip(&v.differentiable_outputs)
            .filter(|(_, d)| **d)
            .map(|(c, _)| Atom::Var(c.clone())),
    );
    let back_outs: Vec<Var> = v.backward.out_avals().into_iter().map(Var::new).collect();
    let call = |body: Function, inputs: Vec<Atom>, outputs: Vec<Var>| Eqn {
        prim: ruxla_prims::JIT,
        inputs,
        params: Params::Jit {
            name: String::from("vjp"),
            body: Arc::new(body),
        },
        outputs,
        loc: None,
    };
    let eqns = vec![
        call(
            v.forward,
            invars.iter().cloned().map(Atom::Var).collect(),
            fwd_outs.clone(),
        ),
        call(v.backward, back_inputs, back_outs.clone()),
    ];
    let mut outvars: Vec<Atom> = fwd_outs[..n_out].iter().cloned().map(Atom::Var).collect();
    let mut cts = back_outs.into_iter();
    for (x, &w) in f.invars.iter().zip(&wrt).skip(skip) {
        outvars.push(if w {
            Atom::Var(cts.next().expect("a cotangent per input"))
        } else {
            let a = x.aval();
            Atom::Lit(Literal::new(HostArray::zeros(a.shape.clone(), a.dtype)))
        });
    }
    let mut all_invars = invars;
    all_invars.extend(ct_vars);
    Function {
        constvars: Vec::new(),
        invars: all_invars,
        eqns,
        outvars,
    }
}

impl<F> VjpFn<F> {
    /// Computes the outputs and the cotangents of the inputs with the
    /// interpreter.
    ///
    /// # Panics
    ///
    /// Panics if the cotangents do not have the types of the outputs, or if
    /// a primitive has no differentiation rule.
    #[track_caller]
    pub fn call<I, O>(&self, primals: &I, cotangents: &O::On<Native>) -> (O::On<Native>, I)
    where
        I: Tree<Native>,
        O: Tree<Trace>,
        O::On<Native>: Tree<Native>,
        F: Fn(I::On<Trace>) -> O,
    {
        let (t, out) = crate::transform::trace_with_output(&self.f, primals);
        assert_eq!(
            t.function.out_avals(),
            native_avals(cotangents),
            "vjp: the cotangents must have the types of the outputs"
        );
        let g = vjp_function(&t.function, 0);
        let mut args = leaves(primals);
        args.extend(leaves(cotangents));
        let mut it = interpret(&g, &args).into_iter();
        let o = out.rebuild::<Native>(&mut it);
        (o, primals.unflatten_like(&mut it))
    }

    /// Computes the outputs and the cotangents of the inputs inside another
    /// trace.
    ///
    /// # Panics
    ///
    /// See [`VjpFn::call`].
    pub fn call_traced<I, O>(&self, primals: I, cotangents: O) -> (O, I)
    where
        I: Tree<Trace>,
        O: Tree<Trace>,
        F: Fn(I) -> O,
    {
        let pa = trace_avals(&primals);
        let (t, out) = trace2(
            |x: I, (): ()| (self.f)(x),
            &pa,
            &[],
            |it| primals.unflatten_like(it),
            |_| (),
        );
        assert_eq!(
            t.function.out_avals()[..],
            trace_avals(&cotangents)[..],
            "vjp: the cotangents must have the types of the outputs"
        );
        let ncap = t.captured.len();
        let g = vjp_function(&t.function, ncap);
        let mut inputs = t.captured;
        inputs.extend(leaves(&primals));
        inputs.extend(leaves(&cotangents));
        let outs = bind_function("vjp", g, &inputs);
        let mut it = outs.into_iter();
        let o = out.unflatten_like(&mut it);
        (o, primals.unflatten_like(&mut it))
    }
}