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
//! Control flow: real branches and loops on `Native`, `cond`, `while`, and
//! `scan` primitives on `Trace`.

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};

/// `if pred { on_true } else { on_false }` for scalars (`lax.select`). Both
/// operands are computed; use [`cond`] to skip work.
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))
}

/// Calls `true_fn(operand)` if `pred` holds and `false_fn(operand)`
/// otherwise (`lax.cond`). On `Native` this is a real branch.
///
/// # Examples
///
/// ```
/// use ruxla_core::{Backend, F32, Native, lax};
///
/// fn relu<B: Backend>(x: F32<B>) -> F32<B> {
///     lax::cond(x.gt(0.0), |x| x, |_| F32::new(0.0), x)
/// }
/// assert_eq!(relu::<Native>(F32::new(-2.0)).value(), 0.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)
}

/// Calls `branches[index]` on `operand`, with the index clamped to the
/// branches (`lax.switch`).
///
/// # Panics
///
/// Panics if there are no branches.
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()
    }
}

/// Repeats `body_fn` while `cond_fn` holds (`lax.while_loop`).
///
/// # Examples
///
/// ```
/// use ruxla_core::{Backend, I32, Native, lax};
///
/// fn collatz_steps<B: Backend>(n: I32<B>) -> I32<B> {
///     let (_, steps) = lax::while_loop(
///         |(n, _): &(I32<B>, I32<B>)| n.gt(1),
///         |(n, s)| (lax::select((n % 2).eq(0), n / 2, n * 3 + 1), s + 1),
///         (n, I32::new(0)),
///     );
///     steps
/// }
/// assert_eq!(collatz_steps::<Native>(I32::new(27)).value(), 111);
/// ```
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)
}

/// `for i in lo..hi { state = body(i, state) }` (`lax.fori_loop`). The
/// bounds are Rust integers or values. On `Trace`, as in JAX, this is a
/// `scan` when both bounds are static, and a `while` otherwise.
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)
}

/// A loop over the leading dimension of the arrays of `xs`: returns the
/// final carry and the outputs stacked along a new leading dimension
/// (`lax.scan`). `length` must match the leading dimension of `xs` (and is
/// the number of iterations when `xs` has no arrays).
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)
}

/// [`scan`] from the end.
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();
    // Every branch takes the values captured by any branch.
    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())
}

/// `select_tree(pred, &on_true(), &on_false())`, computing only the chosen
/// side when the backend can branch (natively); traced, both sides are
/// computed and selected, which gives the same IR as `lax.select` in JAX.
///
/// Use it where a value is computed and then discarded unless a condition
/// holds (a reset at the end of an episode, for example); the closures must
/// be pure, so that skipping one does not change the result.
///
/// # Examples
///
/// ```
/// use ruxla_core::{F32, Native, lax};
///
/// let done = ruxla_core::Bool::<Native>::new(false);
/// let x = lax::select_with(done, || F32::new(0.0), || F32::new(1.5));
/// assert_eq!(x.value(), 1.5);
/// ```
#[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())
    }
}

/// [`select_with`] whose sides take `operand`: natively, the chosen side
/// gets it by value (so that it can update arrays in place, without the
/// copy that a shared array needs); traced, each side gets a copy, and the
/// results are selected (the same IR as `lax.select` of both sides in JAX).
///
/// # Examples
///
/// ```
/// use ruxla_core::{Array, Bool, Native, lax};
///
/// let grid = Array::<Native, f32>::from_vec(vec![0.0; 4], [2, 2]);
/// let left = Bool::<Native>::new(true);
/// let grid = lax::select_with_operand(
///     left,
///     grid,
///     |g| g.into_at((.., 0i64)).set(1.0f32),
///     |g| g.into_at((.., 1i64)).set(1.0f32),
/// );
/// assert_eq!(grid.to_vec(), [1.0, 0.0, 1.0, 0.0]);
/// ```
#[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))
    }
}

/// `f(primals)`, whose derivative in forward mode (and, by linearization,
/// in reverse mode) is given by the rule `jvp`, like `jax.custom_jvp`.
///
/// `jvp` takes the primals and their tangents (of the same structure; the
/// tangents of non-float values are zeros) and returns the outputs and their
/// tangents, which must be linear in the input tangents for reverse mode.
/// Natively, and when the function is not differentiated, `f` is computed.
/// Values that the functions capture are not differentiated.
///
/// # Examples
///
/// ```
/// use ruxla_core::{F32, Trace, grad, lax};
///
/// // log(1 + e^x), with the derivative computed as sigmoid(x) * t.
/// fn softplus<B: ruxla_core::Backend>(x: F32<B>) -> F32<B> {
///     lax::custom_jvp(
///         |x: F32<B>| (x.exp() + 1.0).ln(),
///         |x: F32<B>, t: F32<B>| ((x.exp() + 1.0).ln(), t / ((-x).exp() + 1.0)),
///         x,
///     )
/// }
/// assert_eq!(softplus(F32::<ruxla_core::Native>::new(0.0)).value(), 2f32.ln());
/// let g = grad(|x: F32<Trace>, (): ()| softplus(x)).call(&F32::new(0.0), &());
/// assert_eq!(g.value(), 0.5);
/// ```
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)
}

/// `f(primals)`, whose derivative in reverse mode is given by `fwd` and
/// `bwd`, like `jax.custom_vjp`.
///
/// `fwd` returns the outputs and residuals `R`; `bwd` takes the residuals
/// and the cotangents of the outputs, and returns the cotangents of the
/// primals. `bwd` must not capture traced values (return them from `fwd`).
/// Forward-mode differentiation of the result is not supported, as in JAX.
///
/// # Examples
///
/// ```
/// use ruxla_core::{F32, Trace, grad, lax};
///
/// // The identity in the forward pass, with gradients clipped to [-1, 1].
/// fn clip_gradient<B: ruxla_core::Backend>(x: F32<B>) -> F32<B> {
///     lax::custom_vjp(|x| x, |x| (x, ()), |(), g: F32<B>| g.max(-1.0).min(1.0), x)
/// }
/// let g = grad(|x: F32<Trace>, (): ()| clip_gradient(x * 3.0)).call(&F32::new(1.0), &());
/// assert_eq!(g.value(), 3.0); // 3 * clip(1)
/// ```
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)
}

/// `f(input)`, whose intermediate values reverse-mode differentiation
/// recomputes from the inputs instead of storing (`jax.checkpoint`).
pub fn checkpoint<B: Backend, I: Tree<B>, O: Tree<B>>(f: impl Fn(I) -> O, input: I) -> O {
    B::checkpoint(&f, input)
}

/// Gives traced functions the values that any of them captured: each
/// function takes all the captured values first (in the order of
/// `traced`), then its own arguments.
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");
    // The residuals' types, from the forward function (their values belong
    // to its finished trace).
    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
}