Skip to main content

ruxla_prims/
control.rs

1//! Higher-order primitives, which contain functions.
2
3use std::sync::Arc;
4
5use ruxla_ir::ad::{AdCx, Tangent, TransposeInput};
6use ruxla_ir::batching::{BatchCx, Batched, inline};
7use ruxla_ir::lowering::{HloValue, LowerCx, Region, i64_array};
8use ruxla_ir::{
9    AVal, Atom, DType, Error, EvalCx, Function, HostArray, Params, Prim, Primitive, Result, Shape,
10    Value,
11};
12use ruxla_kernels::{Buffer, with_buffer};
13
14use crate::batching;
15use crate::control_ad as cad;
16use crate::util::{indices, wrong_params};
17
18/// Pairs the outputs of a batched primitive with their batch dimensions:
19/// `bdim` for those that are batched.
20fn with_bdims(outs: Vec<Atom>, batched: &[bool], bdim: usize) -> Vec<Batched> {
21    outs.into_iter()
22        .zip(batched)
23        .map(|(a, &b)| Batched {
24            atom: a,
25            bdim: b.then_some(bdim),
26        })
27        .collect()
28}
29
30fn check_avals(prim: &'static str, what: &str, actual: &[AVal], expected: &[AVal]) -> Result<()> {
31    if actual == expected {
32        Ok(())
33    } else {
34        Err(Error::type_error(
35            prim,
36            format!("{what}: got {actual:?}, expected {expected:?}"),
37        ))
38    }
39}
40
41/// Lowers `f` as a function of the module and emits a call to it.
42pub(crate) fn call(
43    cx: &mut dyn LowerCx,
44    f: &Function,
45    hint: &str,
46    args: &[HloValue],
47) -> Result<Vec<HloValue>> {
48    let symbol = cx.function(f, hint)?;
49    Ok(cx.op(
50        "func.call",
51        args,
52        &format!("callee = @{symbol}"),
53        &f.out_avals(),
54    ))
55}
56
57/// `jit`.
58#[derive(Debug)]
59pub(crate) struct Jit;
60/// Calls a function compiled as a unit ([`Params::Jit`]).
61pub static JIT: Prim = Prim::new(&Jit);
62
63impl Primitive for Jit {
64    fn name(&self) -> &'static str {
65        "jit"
66    }
67    fn abstract_eval(&self, inputs: &[AVal], params: &Params) -> Result<Vec<AVal>> {
68        let Params::Jit { body, .. } = params else {
69            return Err(wrong_params(self.name()));
70        };
71        check_avals(self.name(), "arguments", inputs, &body.in_avals())?;
72        Ok(body.out_avals())
73    }
74    fn eval(
75        &self,
76        cx: &dyn EvalCx,
77        inputs: &[HostArray],
78        params: &Params,
79    ) -> Result<Vec<HostArray>> {
80        let Params::Jit { body, .. } = params else {
81            return Err(wrong_params(self.name()));
82        };
83        cx.eval_function(body, inputs)
84    }
85
86    fn batch(
87        &'static self,
88        cx: &mut dyn BatchCx,
89        inputs: &[Batched],
90        params: &Params,
91    ) -> Result<Vec<Batched>> {
92        let Params::Jit { name, body } = params else {
93            return Err(wrong_params(self.name()));
94        };
95        let in_axes: Vec<Option<usize>> = inputs.iter().map(|x| x.bdim).collect();
96        let force = vec![None; body.outvars.len()];
97        let (body, batched) = cx.batch_function(body, &in_axes, &force)?;
98        let atoms: Vec<Atom> = inputs.iter().map(|x| x.atom.clone()).collect();
99        let outs = cx.bind(
100            JIT,
101            &atoms,
102            Params::Jit {
103                name: name.clone(),
104                body: Arc::new(body),
105            },
106        )?;
107        Ok(with_bdims(outs, &batched, 0))
108    }
109
110    fn lower(
111        &self,
112        cx: &mut dyn LowerCx,
113        inputs: &[HloValue],
114        params: &Params,
115        outputs: &[AVal],
116    ) -> Result<Vec<HloValue>> {
117        let Params::Jit { body, name } = params else {
118            return Err(wrong_params(self.name()));
119        };
120        let symbol = cx.function(body, name)?;
121        let attrs = format!("callee = @{symbol}");
122        Ok(cx.op("func.call", inputs, &attrs, outputs))
123    }
124}
125
126/// `cond`.
127#[derive(Debug)]
128pub(crate) struct Cond;
129/// Calls the branch chosen by an `i32` index, passing the other operands
130/// ([`Params::Cond`]). An index out of range calls the last branch, as
131/// `stablehlo.case` does.
132pub static COND: Prim = Prim::new(&Cond);
133
134impl Primitive for Cond {
135    fn name(&self) -> &'static str {
136        "cond"
137    }
138    fn abstract_eval(&self, inputs: &[AVal], params: &Params) -> Result<Vec<AVal>> {
139        let name = self.name();
140        let Params::Cond { branches } = params else {
141            return Err(wrong_params(name));
142        };
143        let Some((index, ops)) = inputs.split_first() else {
144            return Err(Error::type_error(name, "expected an index"));
145        };
146        if *index != AVal::scalar(DType::I32) {
147            return Err(Error::type_error(
148                name,
149                format!("the index must be an i32 scalar, got {index}"),
150            ));
151        }
152        let Some(first) = branches.first() else {
153            return Err(Error::type_error(name, "expected a branch"));
154        };
155        let outs = first.out_avals();
156        for b in branches {
157            check_avals(name, "branch inputs", ops, &b.in_avals())?;
158            check_avals(name, "branch outputs", &b.out_avals(), &outs)?;
159        }
160        Ok(outs)
161    }
162    fn eval(
163        &self,
164        cx: &dyn EvalCx,
165        inputs: &[HostArray],
166        params: &Params,
167    ) -> Result<Vec<HostArray>> {
168        let Params::Cond { branches } = params else {
169            return Err(wrong_params(self.name()));
170        };
171        let n = branches.len();
172        let i = usize::try_from(indices(&inputs[0])[0])
173            .ok()
174            .filter(|&i| i < n)
175            .unwrap_or(n - 1);
176        cx.eval_function(&branches[i], &inputs[1..])
177    }
178
179    fn batch(
180        &'static self,
181        cx: &mut dyn BatchCx,
182        inputs: &[Batched],
183        params: &Params,
184    ) -> Result<Vec<Batched>> {
185        let Params::Cond { branches } = params else {
186            return Err(wrong_params(self.name()));
187        };
188        let (index, operands) = (&inputs[0], &inputs[1..]);
189        let nout = branches.first().map_or(0, |b| b.outvars.len());
190        if index.bdim.is_none() {
191            // Batch every branch, then again so that all branches batch the
192            // same outputs.
193            let in_axes: Vec<Option<usize>> = operands.iter().map(|x| x.bdim).collect();
194            let mut batched = vec![false; nout];
195            for b in branches {
196                let (_, out) = cx.batch_function(b, &in_axes, &vec![None; nout])?;
197                batched.iter_mut().zip(out).for_each(|(x, o)| *x |= o);
198            }
199            let force: Vec<Option<bool>> = batched.iter().map(|&b| Some(b)).collect();
200            let branches = branches
201                .iter()
202                .map(|b| Ok(Arc::new(cx.batch_function(b, &in_axes, &force)?.0)))
203                .collect::<Result<Vec<_>>>()?;
204            let atoms: Vec<Atom> = inputs.iter().map(|x| x.atom.clone()).collect();
205            let outs = cx.bind(COND, &atoms, Params::Cond { branches })?;
206            return Ok(with_bdims(outs, &batched, 0));
207        }
208        // An index that differs between examples: compute every branch and
209        // select the results, as JAX does.
210        let index = batching::bdim_at_front(cx, index)?;
211        // `cond` calls the last branch for an index out of range (negative
212        // ones too), but `select_n` takes the first case for negative
213        // indices. Reinterpreted as `u32`, negative indices are large, so
214        // clamping them picks the last case. (JAX's `switch` clamps the index
215        // before `cond`, so its batching rule does not need this.)
216        let last = u32::try_from(branches.len().saturating_sub(1))
217            .map_err(|_| Error::unsupported(self.name(), "too many branches"))?;
218        let unsigned = batching::bind1(
219            cx,
220            crate::elementwise::BITCAST_CONVERT_TYPE,
221            &[index],
222            Params::Convert {
223                new_dtype: DType::U32,
224            },
225        )?;
226        let clamped = batching::bind1(
227            cx,
228            crate::elementwise::CLAMP,
229            &[
230                batching::literal(DType::U32, Value::UInt(0)),
231                unsigned,
232                batching::literal(DType::U32, Value::UInt(u64::from(last))),
233            ],
234            Params::None,
235        )?;
236        let index = batching::bind1(
237            cx,
238            crate::elementwise::BITCAST_CONVERT_TYPE,
239            &[clamped],
240            Params::Convert {
241                new_dtype: DType::I32,
242            },
243        )?;
244        let ops = operands
245            .iter()
246            .map(|x| batching::bdim_at_front(cx, x))
247            .collect::<Result<Vec<_>>>()?;
248        let in_axes = vec![Some(0); ops.len()];
249        let force = vec![Some(true); nout];
250        let mut results = Vec::new();
251        for b in branches {
252            let (f, _) = cx.batch_function(b, &in_axes, &force)?;
253            results.push(inline(cx, &f, &ops)?);
254        }
255        let mut outs = Vec::new();
256        for i in 0..nout {
257            let example: Shape = results[0][i].aval().shape.dims()[1..].to_vec().into();
258            let which = batching::broadcast_example_scalar(cx, &index, &example)?;
259            let mut atoms = vec![which];
260            atoms.extend(results.iter().map(|r| r[i].clone()));
261            let out = batching::bind1(cx, crate::elementwise::SELECT_N, &atoms, Params::None)?;
262            outs.push(Batched::mapped(out, 0));
263        }
264        Ok(outs)
265    }
266
267    fn jvp(
268        &'static self,
269        cx: &mut dyn AdCx,
270        primals: &[Atom],
271        tangents: &[Tangent],
272        params: &Params,
273    ) -> Result<(Vec<Atom>, Vec<Tangent>)> {
274        cad::cond_jvp(cx, primals, tangents, params)
275    }
276
277    fn transpose(
278        &'static self,
279        cx: &mut dyn AdCx,
280        cotangents: &[Tangent],
281        inputs: &[TransposeInput],
282        params: &Params,
283    ) -> Result<Vec<Tangent>> {
284        cad::cond_transpose(cx, cotangents, inputs, params)
285    }
286
287    fn lower(
288        &self,
289        cx: &mut dyn LowerCx,
290        inputs: &[HloValue],
291        params: &Params,
292        outputs: &[AVal],
293    ) -> Result<Vec<HloValue>> {
294        let Params::Cond { branches } = params else {
295            return Err(wrong_params(self.name()));
296        };
297        let operands = &inputs[1..];
298        let mut bodies: Vec<_> = branches
299            .iter()
300            .map(|b| move |cx: &mut dyn LowerCx, _: &[HloValue]| call(cx, b, "branch", operands))
301            .collect();
302        let mut regions: Vec<Region<'_>> = bodies
303            .iter_mut()
304            .map(|body| Region {
305                args: Vec::new(),
306                body,
307            })
308            .collect();
309        cx.op_with_regions("stablehlo.case", &inputs[..1], "", &mut regions, outputs)
310    }
311}
312
313/// `while`.
314#[derive(Debug)]
315pub(crate) struct While;
316/// Repeats the body while the predicate holds ([`Params::While`]).
317pub static WHILE: Prim = Prim::new(&While);
318
319impl Primitive for While {
320    fn name(&self) -> &'static str {
321        "while"
322    }
323    fn abstract_eval(&self, inputs: &[AVal], params: &Params) -> Result<Vec<AVal>> {
324        let name = self.name();
325        let Params::While {
326            cond,
327            body,
328            cond_nconsts: nc,
329            body_nconsts: nb,
330        } = params
331        else {
332            return Err(wrong_params(name));
333        };
334        if inputs.len() < nc + nb {
335            return Err(Error::type_error(
336                name,
337                "too few operands for the constants",
338            ));
339        }
340        let carry = &inputs[nc + nb..];
341        let cond_in: Vec<AVal> = inputs[..*nc].iter().chain(carry).cloned().collect();
342        let body_in: Vec<AVal> = inputs[*nc..nc + nb].iter().chain(carry).cloned().collect();
343        check_avals(name, "predicate inputs", &cond_in, &cond.in_avals())?;
344        check_avals(
345            name,
346            "predicate output",
347            &cond.out_avals(),
348            &[AVal::scalar(DType::Bool)],
349        )?;
350        check_avals(name, "body inputs", &body_in, &body.in_avals())?;
351        check_avals(name, "body outputs", &body.out_avals(), carry)?;
352        Ok(carry.to_vec())
353    }
354    fn eval(
355        &self,
356        cx: &dyn EvalCx,
357        inputs: &[HostArray],
358        params: &Params,
359    ) -> Result<Vec<HostArray>> {
360        let Params::While {
361            cond,
362            body,
363            cond_nconsts: nc,
364            body_nconsts: nb,
365        } = params
366        else {
367            return Err(wrong_params(self.name()));
368        };
369        let (cc, bc) = (&inputs[..*nc], &inputs[*nc..nc + nb]);
370        let mut carry = inputs[nc + nb..].to_vec();
371        loop {
372            let args: Vec<HostArray> = cc.iter().chain(&carry).cloned().collect();
373            if !cx.eval_function(cond, &args)?[0].as_slice::<bool>()?[0] {
374                return Ok(carry);
375            }
376            let args: Vec<HostArray> = bc.iter().chain(&carry).cloned().collect();
377            carry = cx.eval_function(body, &args)?;
378        }
379    }
380
381    fn batch(
382        &'static self,
383        cx: &mut dyn BatchCx,
384        inputs: &[Batched],
385        params: &Params,
386    ) -> Result<Vec<Batched>> {
387        let Params::While {
388            cond,
389            body,
390            cond_nconsts: nc,
391            body_nconsts: nb,
392        } = params
393        else {
394            return Err(wrong_params(self.name()));
395        };
396        let (nc, nb) = (*nc, *nb);
397        let axes = |xs: &[Batched]| xs.iter().map(|x| x.bdim).collect::<Vec<_>>();
398        let (cc, bc, init) = (&inputs[..nc], &inputs[nc..nc + nb], &inputs[nc + nb..]);
399        let k = init.len();
400        let carry_axes =
401            |batched: &[bool]| batched.iter().map(|&b| b.then_some(0)).collect::<Vec<_>>();
402
403        // The carries that are batched: those batched initially, and those
404        // that the body makes batched, until nothing changes.
405        let mut batched: Vec<bool> = init.iter().map(|x| x.bdim.is_some()).collect();
406        loop {
407            let in_axes = [axes(bc), carry_axes(&batched)].concat();
408            let (_, out) = cx.batch_function(body, &in_axes, &vec![None; k])?;
409            let next: Vec<bool> = batched.iter().zip(&out).map(|(&a, &b)| a || b).collect();
410            if next == batched {
411                break;
412            }
413            batched = next;
414        }
415        let cond_axes = [axes(cc), carry_axes(&batched)].concat();
416        let (_, pred) = cx.batch_function(cond, &cond_axes, &[None])?;
417
418        if !pred[0] {
419            let force: Vec<Option<bool>> = batched.iter().map(|&b| Some(b)).collect();
420            let (cond_f, _) = cx.batch_function(cond, &cond_axes, &[Some(false)])?;
421            let body_axes = [axes(bc), carry_axes(&batched)].concat();
422            let (body_f, _) = cx.batch_function(body, &body_axes, &force)?;
423            let mut atoms: Vec<Atom> = inputs[..nc + nb].iter().map(|x| x.atom.clone()).collect();
424            for (x, &b) in init.iter().zip(&batched) {
425                atoms.push(if b {
426                    batching::bdim_at_front(cx, x)?
427                } else {
428                    x.atom.clone()
429                });
430            }
431            let outs = cx.bind(
432                WHILE,
433                &atoms,
434                Params::While {
435                    cond: Arc::new(cond_f),
436                    body: Arc::new(body_f),
437                    cond_nconsts: nc,
438                    body_nconsts: nb,
439                },
440            )?;
441            return Ok(with_bdims(outs, &batched, 0));
442        }
443
444        // A predicate that differs between examples: every carry is batched,
445        // the loop runs while any example's predicate holds, and examples
446        // whose predicate fails keep their carry, as in JAX.
447        let all = vec![true; k];
448        let cond_axes = [axes(cc), carry_axes(&all)].concat();
449        let (cond_f, _) = cx.batch_function(cond, &cond_axes, &[Some(true)])?;
450        let body_axes = [axes(bc), carry_axes(&all)].concat();
451        let (body_f, _) = cx.batch_function(body, &body_axes, &vec![Some(true); k])?;
452        let any_cond = cx.build_function(&cond_f.in_avals(), &mut |cx, args| {
453            let pred = inline(cx, &cond_f, args)?.remove(0);
454            Ok(vec![batching::bind1(
455                cx,
456                crate::indexing::REDUCE_MAX,
457                &[pred],
458                Params::Reduce { axes: vec![0] },
459            )?])
460        })?;
461        let cond_in = cond_f.in_avals();
462        let body_in = body_f.in_avals();
463        let mut new_in: Vec<AVal> = cond_in[..nc].to_vec();
464        new_in.extend(body_in.iter().cloned());
465        let select_body = cx.build_function(&new_in, &mut |cx, args| {
466            let (c, rest) = args.split_at(nc);
467            let (b, carry) = rest.split_at(nb);
468            let pred = inline(cx, &cond_f, &[c, carry].concat())?.remove(0);
469            let next = inline(cx, &body_f, &[b, carry].concat())?;
470            carry
471                .iter()
472                .zip(next)
473                .map(|(old, new)| {
474                    let example: Shape = old.aval().shape.dims()[1..].to_vec().into();
475                    let which = batching::broadcast_example_scalar(cx, &pred, &example)?;
476                    batching::bind1(
477                        cx,
478                        crate::elementwise::SELECT_N,
479                        &[which, old.clone(), new],
480                        Params::None,
481                    )
482                })
483                .collect()
484        })?;
485        let mut atoms: Vec<Atom> = cc.iter().map(|x| x.atom.clone()).collect();
486        atoms.extend(inputs[..nc + nb].iter().map(|x| x.atom.clone()));
487        for x in init {
488            atoms.push(batching::bdim_at_front(cx, x)?);
489        }
490        let outs = cx.bind(
491            WHILE,
492            &atoms,
493            Params::While {
494                cond: Arc::new(any_cond),
495                body: Arc::new(select_body),
496                cond_nconsts: nc,
497                body_nconsts: nc + nb,
498            },
499        )?;
500        Ok(with_bdims(outs, &all, 0))
501    }
502
503    fn jvp(
504        &'static self,
505        cx: &mut dyn AdCx,
506        primals: &[Atom],
507        tangents: &[Tangent],
508        params: &Params,
509    ) -> Result<(Vec<Atom>, Vec<Tangent>)> {
510        cad::while_jvp(cx, primals, tangents, params)
511    }
512
513    fn transpose(
514        &'static self,
515        cx: &mut dyn AdCx,
516        cotangents: &[Tangent],
517        inputs: &[TransposeInput],
518        params: &Params,
519    ) -> Result<Vec<Tangent>> {
520        let _ = (cx, cotangents, inputs, params);
521        cad::while_transpose()
522    }
523
524    fn lower(
525        &self,
526        cx: &mut dyn LowerCx,
527        inputs: &[HloValue],
528        params: &Params,
529        outputs: &[AVal],
530    ) -> Result<Vec<HloValue>> {
531        let Params::While {
532            cond,
533            body,
534            cond_nconsts,
535            body_nconsts,
536        } = params
537        else {
538            return Err(wrong_params(self.name()));
539        };
540        let (nc, nb) = (*cond_nconsts, *body_nconsts);
541        // Every operand, constants included, is carried through the loop, so
542        // that the regions only refer to their own arguments.
543        let avals: Vec<AVal> = inputs.iter().map(|v| v.aval.clone()).collect();
544        let mut cond_body = |cx: &mut dyn LowerCx, args: &[HloValue]| {
545            let call_args: Vec<HloValue> =
546                args[..nc].iter().chain(&args[nc + nb..]).cloned().collect();
547            call(cx, cond, "cond", &call_args)
548        };
549        let mut body_body = |cx: &mut dyn LowerCx, args: &[HloValue]| {
550            let next = call(cx, body, "body", &args[nc..])?;
551            Ok(args[..nc + nb].iter().cloned().chain(next).collect())
552        };
553        let mut regions = [
554            Region {
555                args: avals.clone(),
556                body: &mut cond_body,
557            },
558            Region {
559                args: avals.clone(),
560                body: &mut body_body,
561            },
562        ];
563        let results = cx.op_with_regions("stablehlo.while", inputs, "", &mut regions, &avals)?;
564        debug_assert_eq!(results.len() - nc - nb, outputs.len());
565        Ok(results[nc + nb..].to_vec())
566    }
567}
568
569/// `scan`.
570#[derive(Debug)]
571pub(crate) struct Scan;
572/// A loop over the leading dimension of the scanned inputs ([`Params::Scan`]).
573pub static SCAN: Prim = Prim::new(&Scan);
574
575fn drop_leading(a: &AVal) -> AVal {
576    AVal::new(a.shape.dims()[1..].to_vec(), a.dtype)
577}
578
579fn index_leading(x: &HostArray, i: usize) -> HostArray {
580    let inner: usize = x.shape().dims()[1..].iter().product();
581    let b = with_buffer!(x.buffer(), |v| Buffer::from_vec(
582        v[i * inner..(i + 1) * inner].to_vec()
583    ));
584    HostArray::from_buffer(b, x.shape().dims()[1..].to_vec())
585}
586
587fn stack(xs: &[HostArray], aval: &AVal, n: usize) -> HostArray {
588    let mut shape = vec![n];
589    shape.extend_from_slice(&aval.shape);
590    if xs.is_empty() {
591        return HostArray::zeros(shape, aval.dtype);
592    }
593    let b = with_buffer!(xs[0].buffer(), |first| {
594        let mut all = first.clone();
595        for x in &xs[1..] {
596            all.extend_from_slice(x.as_slice().expect("same types"));
597        }
598        Buffer::from_vec(all)
599    });
600    HostArray::from_buffer(b, shape)
601}
602
603impl Primitive for Scan {
604    fn name(&self) -> &'static str {
605        "scan"
606    }
607    fn abstract_eval(&self, inputs: &[AVal], params: &Params) -> Result<Vec<AVal>> {
608        let name = self.name();
609        let Params::Scan {
610            body,
611            length,
612            num_consts,
613            num_carry,
614            ..
615        } = params
616        else {
617            return Err(wrong_params(name));
618        };
619        if inputs.len() < num_consts + num_carry {
620            return Err(Error::type_error(name, "too few operands"));
621        }
622        let xs = &inputs[num_consts + num_carry..];
623        if xs.iter().any(|x| x.shape.first() != Some(length)) {
624            return Err(Error::type_error(
625                name,
626                format!("scanned inputs must have leading dimension {length}"),
627            ));
628        }
629        let mut body_in: Vec<AVal> = inputs[..num_consts + num_carry].to_vec();
630        body_in.extend(xs.iter().map(drop_leading));
631        check_avals(name, "body inputs", &body_in, &body.in_avals())?;
632        let outs = body.out_avals();
633        if outs.len() < *num_carry {
634            return Err(Error::type_error(name, "the body returns too few values"));
635        }
636        check_avals(
637            name,
638            "carry",
639            &outs[..*num_carry],
640            &inputs[*num_consts..num_consts + num_carry],
641        )?;
642        let mut result = outs[..*num_carry].to_vec();
643        result.extend(outs[*num_carry..].iter().map(|a| {
644            let mut s = vec![*length];
645            s.extend_from_slice(&a.shape);
646            AVal::new(s, a.dtype)
647        }));
648        Ok(result)
649    }
650    fn eval(
651        &self,
652        cx: &dyn EvalCx,
653        inputs: &[HostArray],
654        params: &Params,
655    ) -> Result<Vec<HostArray>> {
656        let Params::Scan {
657            body,
658            length,
659            reverse,
660            num_consts,
661            num_carry,
662        } = params
663        else {
664            return Err(wrong_params(self.name()));
665        };
666        let consts = &inputs[..*num_consts];
667        let mut carry = inputs[*num_consts..num_consts + num_carry].to_vec();
668        let xs = &inputs[num_consts + num_carry..];
669        let out_avals = body.out_avals();
670        let mut ys: Vec<Vec<HostArray>> =
671            vec![Vec::with_capacity(*length); out_avals.len() - num_carry];
672        let order: Vec<usize> = if *reverse {
673            (0..*length).rev().collect()
674        } else {
675            (0..*length).collect()
676        };
677        for &i in &order {
678            let mut args: Vec<HostArray> = consts.to_vec();
679            args.extend(carry.iter().cloned());
680            args.extend(xs.iter().map(|x| index_leading(x, i)));
681            let mut outs = cx.eval_function(body, &args)?;
682            let rest = outs.split_off(*num_carry);
683            carry = outs;
684            for (y, v) in ys.iter_mut().zip(rest) {
685                y.push(v);
686            }
687        }
688        if *reverse {
689            ys.iter_mut().for_each(|y| y.reverse());
690        }
691        let mut result = carry;
692        result.extend(
693            ys.iter()
694                .zip(&out_avals[*num_carry..])
695                .map(|(y, a)| stack(y, a, *length)),
696        );
697        Ok(result)
698    }
699
700    fn batch(
701        &'static self,
702        cx: &mut dyn BatchCx,
703        inputs: &[Batched],
704        params: &Params,
705    ) -> Result<Vec<Batched>> {
706        let Params::Scan {
707            body,
708            length,
709            reverse,
710            num_consts,
711            num_carry,
712        } = params
713        else {
714            return Err(wrong_params(self.name()));
715        };
716        let (nconsts, k) = (*num_consts, *num_carry);
717        let (consts, rest) = inputs.split_at(nconsts);
718        let (init, xs) = rest.split_at(k);
719        let nys = body.outvars.len() - k;
720        let const_axes: Vec<Option<usize>> = consts.iter().map(|x| x.bdim).collect();
721        // Scanned inputs are sliced along their first dimension, so their
722        // batch dimension moves to the second; slices have it first.
723        let x_axes: Vec<Option<usize>> = xs.iter().map(|x| x.bdim.map(|_| 0)).collect();
724        let in_axes = |batched: &[bool]| {
725            let mut a = const_axes.clone();
726            a.extend(batched.iter().map(|&b| b.then_some(0)));
727            a.extend(x_axes.iter().copied());
728            a
729        };
730        // The carries that are batched, widened to a fixed point.
731        let mut batched: Vec<bool> = init.iter().map(|x| x.bdim.is_some()).collect();
732        loop {
733            let (_, out) = cx.batch_function(body, &in_axes(&batched), &vec![None; k + nys])?;
734            let next: Vec<bool> = batched.iter().zip(&out).map(|(&a, &b)| a || b).collect();
735            if next == batched {
736                break;
737            }
738            batched = next;
739        }
740        let mut force: Vec<Option<bool>> = batched.iter().map(|&b| Some(b)).collect();
741        force.extend(std::iter::repeat_n(None, nys));
742        let (body_f, out) = cx.batch_function(body, &in_axes(&batched), &force)?;
743
744        let mut atoms: Vec<Atom> = consts.iter().map(|x| x.atom.clone()).collect();
745        for (x, &b) in init.iter().zip(&batched) {
746            atoms.push(if b {
747                batching::bdim_at_front(cx, x)?
748            } else {
749                x.atom.clone()
750            });
751        }
752        for x in xs {
753            atoms.push(match x.bdim {
754                Some(_) => batching::move_bdim(cx, x, 1)?,
755                None => x.atom.clone(),
756            });
757        }
758        let outs = cx.bind(
759            SCAN,
760            &atoms,
761            Params::Scan {
762                body: Arc::new(body_f),
763                length: *length,
764                reverse: *reverse,
765                num_consts: nconsts,
766                num_carry: k,
767            },
768        )?;
769        let (carry, ys) = outs.split_at(k);
770        let mut result = with_bdims(carry.to_vec(), &batched, 0);
771        result.extend(with_bdims(ys.to_vec(), &out[k..], 1));
772        Ok(result)
773    }
774
775    fn jvp(
776        &'static self,
777        cx: &mut dyn AdCx,
778        primals: &[Atom],
779        tangents: &[Tangent],
780        params: &Params,
781    ) -> Result<(Vec<Atom>, Vec<Tangent>)> {
782        cad::scan_jvp(cx, primals, tangents, params)
783    }
784
785    fn transpose(
786        &'static self,
787        cx: &mut dyn AdCx,
788        cotangents: &[Tangent],
789        inputs: &[TransposeInput],
790        params: &Params,
791    ) -> Result<Vec<Tangent>> {
792        cad::scan_transpose(cx, cotangents, inputs, params)
793    }
794
795    fn lower(
796        &self,
797        cx: &mut dyn LowerCx,
798        inputs: &[HloValue],
799        params: &Params,
800        outputs: &[AVal],
801    ) -> Result<Vec<HloValue>> {
802        let Params::Scan {
803            body,
804            length,
805            reverse,
806            num_consts,
807            num_carry,
808        } = params
809        else {
810            return Err(wrong_params(self.name()));
811        };
812        let (nk, nc, n) = (*num_consts, *num_carry, *length);
813        let nx = inputs.len() - nk - nc;
814        let ny = outputs.len() - nc;
815        let i32_scalar = AVal::scalar(DType::I32);
816        // Without iterations, the carry is unchanged and the outputs are
817        // empty (a loop would slice the empty scanned operands).
818        if n == 0 {
819            let mut outs = inputs[nk..nk + nc].to_vec();
820            for y in &outputs[nc..] {
821                outs.push(cx.splat(Value::Int(0), y));
822            }
823            return Ok(outs);
824        }
825
826        // Loop variables: the counter, the constants, the carry, the scanned
827        // operands, and the stacked outputs (initially zeros).
828        let zero = cx.splat(Value::Int(0), &i32_scalar);
829        let mut init = vec![zero];
830        init.extend_from_slice(inputs);
831        for y in &outputs[nc..] {
832            init.push(cx.splat(Value::Int(0), y));
833        }
834        let avals: Vec<AVal> = init.iter().map(|v| v.aval.clone()).collect();
835
836        let mut cond_body = |cx: &mut dyn LowerCx, args: &[HloValue]| {
837            let limit = cx.splat(Value::Int(n as i64), &i32_scalar);
838            Ok(vec![crate::elementwise::compare(
839                cx,
840                "LT",
841                &args[0],
842                &limit,
843                &AVal::scalar(DType::Bool),
844            )])
845        };
846        let mut body_body = |cx: &mut dyn LowerCx, args: &[HloValue]| {
847            let counter = &args[0];
848            let consts = &args[1..1 + nk];
849            let carry = &args[1 + nk..1 + nk + nc];
850            let xs = &args[1 + nk + nc..1 + nk + nc + nx];
851            let ys = &args[1 + nk + nc + nx..];
852            let index = if *reverse {
853                let last = cx.splat(Value::Int(n as i64 - 1), &i32_scalar);
854                cx.op1(
855                    "stablehlo.subtract",
856                    &[last, counter.clone()],
857                    "",
858                    &i32_scalar,
859                )
860            } else {
861                counter.clone()
862            };
863            let zero = cx.splat(Value::Int(0), &i32_scalar);
864            let starts = |rank: usize| -> Vec<HloValue> {
865                std::iter::once(index.clone())
866                    .chain(std::iter::repeat_n(zero.clone(), rank - 1))
867                    .collect()
868            };
869
870            let mut call_args: Vec<HloValue> = consts.iter().chain(carry).cloned().collect();
871            for x in xs {
872                let mut sizes = x.aval.shape.to_vec();
873                sizes[0] = 1;
874                let mut operands = vec![x.clone()];
875                operands.extend(starts(sizes.len()));
876                let slice_aval = AVal::new(sizes.clone(), x.aval.dtype);
877                let slice = cx.op1(
878                    "stablehlo.dynamic_slice",
879                    &operands,
880                    &format!("slice_sizes = {}", i64_array(&sizes)),
881                    &slice_aval,
882                );
883                let item = AVal::new(x.aval.shape[1..].to_vec(), x.aval.dtype);
884                call_args.push(cx.op1("stablehlo.reshape", &[slice], "", &item));
885            }
886            let outs = call(cx, body, "scan_body", &call_args)?;
887            let (new_carry, y_slices) = outs.split_at(nc);
888
889            let mut new_ys = Vec::with_capacity(ny);
890            for (stack, y) in ys.iter().zip(y_slices) {
891                let mut dims = vec![1];
892                dims.extend_from_slice(&y.aval.shape);
893                let update = cx.op1(
894                    "stablehlo.reshape",
895                    std::slice::from_ref(y),
896                    "",
897                    &AVal::new(dims, y.aval.dtype),
898                );
899                let mut operands = vec![stack.clone(), update];
900                operands.extend(starts(stack.aval.shape.rank()));
901                new_ys.push(cx.op1("stablehlo.dynamic_update_slice", &operands, "", &stack.aval));
902            }
903            let one = cx.splat(Value::Int(1), &i32_scalar);
904            let next = cx.op1("stablehlo.add", &[counter.clone(), one], "", &i32_scalar);
905            Ok(std::iter::once(next)
906                .chain(consts.iter().cloned())
907                .chain(new_carry.iter().cloned())
908                .chain(xs.iter().cloned())
909                .chain(new_ys)
910                .collect())
911        };
912        let mut regions = [
913            Region {
914                args: avals.clone(),
915                body: &mut cond_body,
916            },
917            Region {
918                args: avals.clone(),
919                body: &mut body_body,
920            },
921        ];
922        let results = cx.op_with_regions("stablehlo.while", &init, "", &mut regions, &avals)?;
923        let carry = &results[1 + nk..1 + nk + nc];
924        let ys = &results[1 + nk + nc + nx..];
925        Ok(carry.iter().chain(ys).cloned().collect())
926    }
927}