Skip to main content

ruxla_prims/
indexing.rs

1//! Reductions, `dot_general`, `gather`, and the scatter family.
2
3use ruxla_ir::Atom;
4use ruxla_ir::ad::{AdCx, Tangent, TransposeInput};
5use ruxla_ir::batching::{BatchCx, Batched};
6use ruxla_ir::lowering::{HloValue, LowerCx, Region, i64_array};
7use ruxla_ir::{
8    AVal, DType, DotDims, Error, EvalCx, GatherDims, GatherScatterMode, HostArray, Params,
9    Precision, Prim, Primitive, Result, ScatterDims, Shape, Value,
10};
11use ruxla_kernels::array::{self as k, ReduceOp};
12use ruxla_kernels::{BinaryOp, Buffer, Element, Ops, with_buffer, with_dtype};
13
14use crate::batching::{self, batched_operand, bdim_at_front};
15use crate::elementwise::compare;
16use crate::indexing_ad as iad;
17use crate::structural_ad as sad;
18use crate::util::{arity, check_axes, indices, integer, wrong_params};
19
20/// `reduce_sum`, `reduce_max`, `reduce_min`.
21#[derive(Debug)]
22pub(crate) struct Reduce {
23    name: &'static str,
24    op: ReduceOp,
25}
26
27/// Sums over axes ([`Params::Reduce`]).
28pub static REDUCE_SUM: Prim = Prim::new(&Reduce {
29    name: "reduce_sum",
30    op: ReduceOp::Sum,
31});
32/// The maximum over axes, propagating NaN (logical or for booleans).
33pub static REDUCE_MAX: Prim = Prim::new(&Reduce {
34    name: "reduce_max",
35    op: ReduceOp::Max,
36});
37/// The minimum over axes, propagating NaN (logical and for booleans).
38pub static REDUCE_MIN: Prim = Prim::new(&Reduce {
39    name: "reduce_min",
40    op: ReduceOp::Min,
41});
42
43impl Primitive for Reduce {
44    fn name(&self) -> &'static str {
45        self.name
46    }
47    fn abstract_eval(&self, inputs: &[AVal], params: &Params) -> Result<Vec<AVal>> {
48        arity(self.name, inputs, 1)?;
49        let Params::Reduce { axes } = params else {
50            return Err(wrong_params(self.name));
51        };
52        let x = &inputs[0];
53        if !self.op.binary().supports(x.dtype) {
54            return Err(Error::type_error(
55                self.name,
56                format!("does not accept {} operands", x.dtype),
57            ));
58        }
59        check_axes(self.name, axes, x.shape.rank())?;
60        Ok(vec![AVal::new(k::reduced_shape(&x.shape, axes), x.dtype)])
61    }
62    fn eval(
63        &self,
64        _: &dyn EvalCx,
65        inputs: &[HostArray],
66        params: &Params,
67    ) -> Result<Vec<HostArray>> {
68        let Params::Reduce { axes } = params else {
69            return Err(wrong_params(self.name));
70        };
71        let x = &inputs[0];
72        let b = with_buffer!(x.buffer(), |v| Buffer::from_vec(k::reduce(
73            v,
74            x.shape(),
75            axes,
76            self.op
77        )));
78        Ok(vec![HostArray::from_buffer(
79            b,
80            k::reduced_shape(x.shape(), axes),
81        )])
82    }
83
84    fn batch(
85        &'static self,
86        cx: &mut dyn BatchCx,
87        inputs: &[Batched],
88        params: &Params,
89    ) -> Result<Vec<Batched>> {
90        let Params::Reduce { axes } = params else {
91            return Err(wrong_params(self.name));
92        };
93        let x = &inputs[0];
94        let b = batched_operand(self.name, x)?;
95        let axes: Vec<usize> = axes.iter().map(|&a| batching::batched_dim(a, b)).collect();
96        let before = axes.iter().filter(|&&a| a < b).count();
97        let out = batching::bind1(
98            cx,
99            Prim::new(self),
100            std::slice::from_ref(&x.atom),
101            Params::Reduce { axes },
102        )?;
103        Ok(vec![Batched::mapped(out, b - before)])
104    }
105
106    fn lower(
107        &self,
108        cx: &mut dyn LowerCx,
109        inputs: &[HloValue],
110        params: &Params,
111        outputs: &[AVal],
112    ) -> Result<Vec<HloValue>> {
113        let Params::Reduce { axes } = params else {
114            return Err(wrong_params(self.name));
115        };
116        let x = &inputs[0];
117        let dtype = x.aval.dtype;
118        let init = cx.constant(&identity(self.op, dtype));
119        let scalar = AVal::scalar(dtype);
120        let op = self.op;
121        let mut body = |cx: &mut dyn LowerCx, args: &[HloValue]| {
122            let (a, b) = (&args[0], &args[1]);
123            // Booleans reduce with `or` and `and`, as JAX's `reduce_or` and
124            // `reduce_and` do.
125            Ok(vec![match (op, dtype) {
126                (ReduceOp::Sum, _) => cx.op1("stablehlo.add", args, "", &scalar),
127                (ReduceOp::Max, DType::Bool) => cx.op1("stablehlo.or", args, "", &scalar),
128                (ReduceOp::Min, DType::Bool) => cx.op1("stablehlo.and", args, "", &scalar),
129                (ReduceOp::Max, _) => cx.min_max("stablehlo.maximum", a, b, &scalar),
130                (ReduceOp::Min, _) => cx.min_max("stablehlo.minimum", a, b, &scalar),
131            }])
132        };
133        let mut regions = [Region {
134            args: vec![AVal::scalar(dtype), AVal::scalar(dtype)],
135            body: &mut body,
136        }];
137        let attrs = format!("dimensions = {}", i64_array(axes));
138        cx.op_with_regions(
139            "stablehlo.reduce",
140            &[x.clone(), init],
141            &attrs,
142            &mut regions,
143            outputs,
144        )
145    }
146
147    fn jvp(
148        &'static self,
149        cx: &mut dyn AdCx,
150        primals: &[Atom],
151        tangents: &[Tangent],
152        params: &Params,
153    ) -> Result<(Vec<Atom>, Vec<Tangent>)> {
154        if self.op != ReduceOp::Sum {
155            return iad::reduce_chooser_jvp(cx, Prim::new(self), &primals[0], &tangents[0], params);
156        }
157        sad::linear_jvp(cx, Prim::new(self), primals, tangents, params)
158    }
159
160    fn transpose(
161        &'static self,
162        cx: &mut dyn AdCx,
163        cotangents: &[Tangent],
164        inputs: &[TransposeInput],
165        params: &Params,
166    ) -> Result<Vec<Tangent>> {
167        sad::reduce_sum_transpose(cx, self.op, &cotangents[0], &inputs[0], params)
168    }
169}
170
171/// `argmax`, `argmin`.
172#[derive(Debug)]
173pub(crate) struct ArgMinMax {
174    max: bool,
175}
176
177/// The index of the largest element along an axis ([`Params::ArgMinMax`]).
178pub static ARGMAX: Prim = Prim::new(&ArgMinMax { max: true });
179/// The index of the smallest element along an axis.
180pub static ARGMIN: Prim = Prim::new(&ArgMinMax { max: false });
181
182impl Primitive for ArgMinMax {
183    fn name(&self) -> &'static str {
184        if self.max { "argmax" } else { "argmin" }
185    }
186    fn abstract_eval(&self, inputs: &[AVal], params: &Params) -> Result<Vec<AVal>> {
187        arity(self.name(), inputs, 1)?;
188        let Params::ArgMinMax { axis, index_dtype } = params else {
189            return Err(wrong_params(self.name()));
190        };
191        let x = &inputs[0];
192        check_axes(self.name(), &[*axis], x.shape.rank())?;
193        if !index_dtype.is_int()
194            || x.dtype == DType::Bool
195            || x.dtype.is_complex()
196            || x.shape[*axis] == 0
197        {
198            return Err(Error::type_error(
199                self.name(),
200                format!("cannot take the {} of {x} along {axis}", self.name()),
201            ));
202        }
203        Ok(vec![AVal::new(
204            k::reduced_shape(&x.shape, &[*axis]),
205            *index_dtype,
206        )])
207    }
208    fn eval(
209        &self,
210        _: &dyn EvalCx,
211        inputs: &[HostArray],
212        params: &Params,
213    ) -> Result<Vec<HostArray>> {
214        let Params::ArgMinMax { axis, index_dtype } = params else {
215            return Err(wrong_params(self.name()));
216        };
217        let x = &inputs[0];
218        let idx = with_buffer!(x.buffer(), |v| k::arg_min_max(
219            v,
220            x.shape(),
221            *axis,
222            self.max
223        ));
224        let shape = k::reduced_shape(x.shape(), &[*axis]);
225        Ok(vec![HostArray::from_vec(idx, shape).convert(*index_dtype)])
226    }
227
228    fn batch(
229        &'static self,
230        cx: &mut dyn BatchCx,
231        inputs: &[Batched],
232        params: &Params,
233    ) -> Result<Vec<Batched>> {
234        let Params::ArgMinMax { axis, index_dtype } = params else {
235            return Err(wrong_params(self.name()));
236        };
237        let x = &inputs[0];
238        let b = batched_operand(self.name(), x)?;
239        let axis = batching::batched_dim(*axis, b);
240        let out = batching::bind1(
241            cx,
242            Prim::new(self),
243            std::slice::from_ref(&x.atom),
244            Params::ArgMinMax {
245                axis,
246                index_dtype: *index_dtype,
247            },
248        )?;
249        Ok(vec![Batched::mapped(out, if axis < b { b - 1 } else { b })])
250    }
251
252    fn lower(
253        &self,
254        cx: &mut dyn LowerCx,
255        inputs: &[HloValue],
256        params: &Params,
257        outputs: &[AVal],
258    ) -> Result<Vec<HloValue>> {
259        let Params::ArgMinMax { axis, index_dtype } = *params else {
260            return Err(wrong_params(self.name()));
261        };
262        let x = &inputs[0];
263        let dtype = x.aval.dtype;
264        // A variadic reduce over (value, index), as JAX lowers argmax.
265        let iota_aval = AVal::new(x.aval.shape.clone(), index_dtype);
266        let iota = cx.op1(
267            "stablehlo.iota",
268            &[],
269            &format!("iota_dimension = {axis} : i64"),
270            &iota_aval,
271        );
272        let op = if self.max {
273            ReduceOp::Max
274        } else {
275            ReduceOp::Min
276        };
277        let init_value = cx.constant(&identity(op, dtype));
278        let init_index = cx.constant(&HostArray::zeros(Shape::scalar(), index_dtype));
279        let value_aval = AVal::scalar(dtype);
280        let index_aval = AVal::scalar(index_dtype);
281        let bool_aval = AVal::scalar(DType::Bool);
282        let max = self.max;
283        let mut body = |cx: &mut dyn LowerCx, args: &[HloValue]| {
284            // As in JAX's lowering, the first value and index are the operand
285            // that may replace the accumulator, which comes second.
286            let (op_v, op_i, acc_v, acc_i) = (&args[0], &args[1], &args[2], &args[3]);
287            // Pick the operand if it is better, or if it is NaN.
288            let better = compare(cx, if max { "GT" } else { "LT" }, op_v, acc_v, &bool_aval);
289            let pick_value = if dtype.is_float() {
290                let nan = compare(cx, "NE", op_v, op_v, &bool_aval);
291                cx.op1("stablehlo.or", &[better, nan], "", &bool_aval)
292            } else {
293                better
294            };
295            // On ties, pick the first index.
296            let equal = compare(cx, "EQ", op_v, acc_v, &bool_aval);
297            let earlier = compare(cx, "LT", op_i, acc_i, &bool_aval);
298            let tie = cx.op1("stablehlo.and", &[equal, earlier], "", &bool_aval);
299            let pick_index = cx.op1("stablehlo.or", &[pick_value.clone(), tie], "", &bool_aval);
300            let v = cx.op1(
301                "stablehlo.select",
302                &[pick_value, op_v.clone(), acc_v.clone()],
303                "",
304                &value_aval,
305            );
306            let i = cx.op1(
307                "stablehlo.select",
308                &[pick_index, op_i.clone(), acc_i.clone()],
309                "",
310                &index_aval,
311            );
312            Ok(vec![v, i])
313        };
314        let mut regions = [Region {
315            args: vec![
316                AVal::scalar(dtype),
317                AVal::scalar(index_dtype),
318                AVal::scalar(dtype),
319                AVal::scalar(index_dtype),
320            ],
321            body: &mut body,
322        }];
323        let value_out = AVal::new(outputs[0].shape.clone(), dtype);
324        let results = cx.op_with_regions(
325            "stablehlo.reduce",
326            &[x.clone(), iota, init_value, init_index],
327            &format!("dimensions = array<i64: {axis}>"),
328            &mut regions,
329            &[value_out, outputs[0].clone()],
330        )?;
331        Ok(vec![results[1].clone()])
332    }
333}
334
335/// `dot_general`.
336#[derive(Debug)]
337pub(crate) struct DotGeneral;
338
339/// Sums of products over contracting dimensions ([`Params::DotGeneral`]).
340pub static DOT_GENERAL: Prim = Prim::new(&DotGeneral);
341
342impl Primitive for DotGeneral {
343    fn name(&self) -> &'static str {
344        "dot_general"
345    }
346    fn abstract_eval(&self, inputs: &[AVal], params: &Params) -> Result<Vec<AVal>> {
347        let name = self.name();
348        arity(name, inputs, 2)?;
349        let Params::DotGeneral {
350            dimension_numbers: d,
351            preferred_element_type,
352            ..
353        } = params
354        else {
355            return Err(wrong_params(name));
356        };
357        let (l, r) = (&inputs[0], &inputs[1]);
358        if l.dtype != r.dtype || l.dtype == DType::Bool {
359            return Err(Error::type_error(
360                name,
361                format!("cannot multiply {l} and {r}"),
362            ));
363        }
364        if let Some(to) = preferred_element_type {
365            let from = l.dtype;
366            let compatible = if from.is_int() {
367                to.is_int() || to.is_float()
368            } else {
369                to.is_float()
370            };
371            if !compatible || to.size_in_bytes() < from.size_in_bytes() {
372                return Err(Error::type_error(
373                    name,
374                    format!("cannot compute a product of {from} as {to}"),
375                ));
376            }
377        }
378        if d.lhs_contracting.len() != d.rhs_contracting.len()
379            || d.lhs_batch.len() != d.rhs_batch.len()
380        {
381            return Err(Error::type_error(
382                name,
383                format!("mismatched dimension numbers {d:?}"),
384            ));
385        }
386        let ld: Vec<usize> = d
387            .lhs_contracting
388            .iter()
389            .chain(&d.lhs_batch)
390            .copied()
391            .collect();
392        let rd: Vec<usize> = d
393            .rhs_contracting
394            .iter()
395            .chain(&d.rhs_batch)
396            .copied()
397            .collect();
398        check_axes(name, &ld, l.shape.rank())?;
399        check_axes(name, &rd, r.shape.rank())?;
400        if ld.iter().zip(&rd).any(|(&a, &b)| l.shape[a] != r.shape[b]) {
401            return Err(Error::type_error(
402                name,
403                format!("contracted and batch dimensions of {l} and {r} differ"),
404            ));
405        }
406        Ok(vec![AVal::new(
407            k::dot_shape(&l.shape, &r.shape, d),
408            preferred_element_type.unwrap_or(l.dtype),
409        )])
410    }
411    fn eval(
412        &self,
413        _: &dyn EvalCx,
414        inputs: &[HostArray],
415        params: &Params,
416    ) -> Result<Vec<HostArray>> {
417        let Params::DotGeneral {
418            dimension_numbers: d,
419            preferred_element_type,
420            ..
421        } = params
422        else {
423            return Err(wrong_params(self.name()));
424        };
425        let to = preferred_element_type.unwrap_or(inputs[0].dtype());
426        // The operands are converted to the result type, then multiplied.
427        let (l, r) = (inputs[0].convert(to), inputs[1].convert(to));
428        let shape = k::dot_shape(l.shape(), r.shape(), d);
429        let b = with_buffer!(l.buffer(), |a| Buffer::from_vec(k::dot_general(
430            a,
431            l.shape(),
432            r.as_slice().expect("same types"),
433            r.shape(),
434            d
435        )));
436        Ok(vec![HostArray::from_buffer(b, shape)])
437    }
438
439    fn batch(
440        &'static self,
441        cx: &mut dyn BatchCx,
442        inputs: &[Batched],
443        params: &Params,
444    ) -> Result<Vec<Batched>> {
445        let Params::DotGeneral {
446            dimension_numbers: d,
447            precision,
448            preferred_element_type,
449        } = params
450        else {
451            return Err(wrong_params(self.name()));
452        };
453        let (lhs, rhs) = (&inputs[0], &inputs[1]);
454        let shift = |dims: &[usize], b: usize| -> Vec<usize> {
455            dims.iter().map(|&i| batching::batched_dim(i, b)).collect()
456        };
457        // The number of free dimensions of an example operand before `b`.
458        let free_before = |rank: usize, contracting: &[usize], batch: &[usize], b: usize| {
459            k::free_dims(rank, contracting, batch)
460                .iter()
461                .filter(|&&i| i < b)
462                .count()
463        };
464        let nbatch = d.lhs_batch.len();
465        // As in JAX's `_dot_general_batch_dim_nums`.
466        let (dims, bdim) = match (lhs.bdim, rhs.bdim) {
467            // Both batched: the batch becomes the first batch dimension.
468            (Some(lb), Some(rb)) => (
469                DotDims {
470                    lhs_contracting: shift(&d.lhs_contracting, lb),
471                    rhs_contracting: shift(&d.rhs_contracting, rb),
472                    lhs_batch: [vec![lb], shift(&d.lhs_batch, lb)].concat(),
473                    rhs_batch: [vec![rb], shift(&d.rhs_batch, rb)].concat(),
474                },
475                0,
476            ),
477            // One batched: the batch becomes a free dimension of that operand.
478            (Some(b), None) => {
479                let rank = lhs.example_aval().shape.rank();
480                let bdim = nbatch + free_before(rank, &d.lhs_contracting, &d.lhs_batch, b);
481                (
482                    DotDims {
483                        lhs_contracting: shift(&d.lhs_contracting, b),
484                        lhs_batch: shift(&d.lhs_batch, b),
485                        ..d.clone()
486                    },
487                    bdim,
488                )
489            }
490            (None, Some(b)) => {
491                let lhs_rank = lhs.atom.aval().shape.rank();
492                let rank = rhs.example_aval().shape.rank();
493                let bdim = lhs_rank - d.lhs_contracting.len()
494                    + free_before(rank, &d.rhs_contracting, &d.rhs_batch, b);
495                (
496                    DotDims {
497                        rhs_contracting: shift(&d.rhs_contracting, b),
498                        rhs_batch: shift(&d.rhs_batch, b),
499                        ..d.clone()
500                    },
501                    bdim,
502                )
503            }
504            (None, None) => {
505                return Err(Error::Malformed(String::from(
506                    "the batching rule of dot_general was called without batched operands",
507                )));
508            }
509        };
510        let out = batching::bind1(
511            cx,
512            DOT_GENERAL,
513            &[lhs.atom.clone(), rhs.atom.clone()],
514            Params::DotGeneral {
515                dimension_numbers: dims,
516                precision: *precision,
517                preferred_element_type: *preferred_element_type,
518            },
519        )?;
520        Ok(vec![Batched::mapped(out, bdim)])
521    }
522
523    fn lower(
524        &self,
525        cx: &mut dyn LowerCx,
526        inputs: &[HloValue],
527        params: &Params,
528        outputs: &[AVal],
529    ) -> Result<Vec<HloValue>> {
530        let Params::DotGeneral {
531            dimension_numbers: d,
532            precision,
533            ..
534        } = params
535        else {
536            return Err(wrong_params(self.name()));
537        };
538        let list = |v: &[usize]| {
539            v.iter()
540                .map(ToString::to_string)
541                .collect::<Vec<_>>()
542                .join(", ")
543        };
544        let mut fields = Vec::new();
545        for (name, dims) in [
546            ("lhs_batching_dimensions", &d.lhs_batch),
547            ("rhs_batching_dimensions", &d.rhs_batch),
548            ("lhs_contracting_dimensions", &d.lhs_contracting),
549            ("rhs_contracting_dimensions", &d.rhs_contracting),
550        ] {
551            if !dims.is_empty() {
552                fields.push(format!("{name} = [{}]", list(dims)));
553            }
554        }
555        let precision = match precision {
556            Precision::Default => "DEFAULT",
557            Precision::High => "HIGH",
558            Precision::Highest => "HIGHEST",
559        };
560        let attrs = format!(
561            "dot_dimension_numbers = #stablehlo.dot<{}>, precision_config = \
562             [#stablehlo<precision {precision}>, #stablehlo<precision {precision}>]",
563            fields.join(", ")
564        );
565        Ok(vec![cx.op1(
566            "stablehlo.dot_general",
567            inputs,
568            &attrs,
569            &outputs[0],
570        )])
571    }
572
573    fn jvp(
574        &'static self,
575        cx: &mut dyn AdCx,
576        primals: &[Atom],
577        tangents: &[Tangent],
578        params: &Params,
579    ) -> Result<(Vec<Atom>, Vec<Tangent>)> {
580        sad::dot_general_jvp(cx, primals, tangents, params)
581    }
582
583    fn transpose(
584        &'static self,
585        cx: &mut dyn AdCx,
586        cotangents: &[Tangent],
587        inputs: &[TransposeInput],
588        params: &Params,
589    ) -> Result<Vec<Tangent>> {
590        sad::dot_general_transpose(cx, &cotangents[0], inputs, params)
591    }
592}
593
594fn sorted_unique(name: &'static str, what: &str, dims: &[usize], rank: usize) -> Result<()> {
595    if dims.windows(2).any(|w| w[0] >= w[1]) || dims.iter().any(|&d| d >= rank) {
596        return Err(Error::type_error(
597            name,
598            format!("{what} {dims:?} must be sorted, distinct, and less than {rank}"),
599        ));
600    }
601    Ok(())
602}
603
604fn check_indices(name: &'static str, idx: &AVal, n: usize) -> Result<usize> {
605    integer(name, idx)?;
606    let q = idx.shape.rank();
607    if q == 0 || idx.shape[q - 1] != n {
608        return Err(Error::type_error(
609            name,
610            format!("the last dimension of the indices {idx} must have size {n}"),
611        ));
612    }
613    Ok(q)
614}
615
616/// `gather`.
617#[derive(Debug)]
618pub(crate) struct Gather;
619
620/// Slices at run-time start indices ([`Params::Gather`]).
621pub static GATHER: Prim = Prim::new(&Gather);
622
623fn gather_check(x: &AVal, idx: &AVal, d: &GatherDims, sizes: &[usize]) -> Result<Vec<usize>> {
624    let name = "gather";
625    let r = x.shape.rank();
626    let q = check_indices(name, idx, d.start_index_map.len())?;
627    if sizes.len() != r || sizes.iter().zip(x.shape.dims()).any(|(s, n)| s > n) {
628        return Err(Error::type_error(
629            name,
630            format!("invalid slice sizes {sizes:?} for {x}"),
631        ));
632    }
633    sorted_unique(name, "collapsed_slice_dims", &d.collapsed_slice_dims, r)?;
634    sorted_unique(name, "operand_batching_dims", &d.operand_batching_dims, r)?;
635    sorted_unique(
636        name,
637        "offset_dims",
638        &d.offset_dims,
639        d.offset_dims.len() + q - 1,
640    )?;
641    let batching_ok = d.start_indices_batching_dims.len() == d.operand_batching_dims.len()
642        && d.start_indices_batching_dims.iter().all(|&b| b < q - 1)
643        && d.operand_batching_dims
644            .iter()
645            .zip(&d.start_indices_batching_dims)
646            .all(|(&o, &i)| x.shape[o] == idx.shape[i] && sizes[o] == 1);
647    let map_ok = d
648        .start_index_map
649        .iter()
650        .all(|m| *m < r && !d.operand_batching_dims.contains(m));
651    let collapsed_ok = d
652        .collapsed_slice_dims
653        .iter()
654        .all(|c| sizes[*c] <= 1 && !d.operand_batching_dims.contains(c));
655    let windowed = r - d.collapsed_slice_dims.len() - d.operand_batching_dims.len();
656    if !batching_ok || !map_ok || !collapsed_ok || windowed != d.offset_dims.len() {
657        return Err(Error::type_error(
658            name,
659            format!("invalid dimension numbers {d:?} for {x} and {idx}"),
660        ));
661    }
662    Ok(k::gather_shape(&idx.shape, d, sizes))
663}
664
665impl Primitive for Gather {
666    fn name(&self) -> &'static str {
667        "gather"
668    }
669    fn abstract_eval(&self, inputs: &[AVal], params: &Params) -> Result<Vec<AVal>> {
670        arity(self.name(), inputs, 2)?;
671        let Params::Gather {
672            dimension_numbers,
673            slice_sizes,
674            mode,
675            ..
676        } = params
677        else {
678            return Err(wrong_params(self.name()));
679        };
680        if *mode == ruxla_ir::GatherScatterMode::FillOrDrop {
681            return Err(Error::unsupported(
682                self.name(),
683                "the fill mode is not implemented yet",
684            ));
685        }
686        let shape = gather_check(&inputs[0], &inputs[1], dimension_numbers, slice_sizes)?;
687        Ok(vec![AVal::new(shape, inputs[0].dtype)])
688    }
689    fn eval(
690        &self,
691        _: &dyn EvalCx,
692        inputs: &[HostArray],
693        params: &Params,
694    ) -> Result<Vec<HostArray>> {
695        let Params::Gather {
696            dimension_numbers: d,
697            slice_sizes,
698            ..
699        } = params
700        else {
701            return Err(wrong_params(self.name()));
702        };
703        let (x, idx) = (&inputs[0], &inputs[1]);
704        let iv = indices(idx);
705        let shape = k::gather_shape(idx.shape(), d, slice_sizes);
706        let b = with_buffer!(x.buffer(), |v| Buffer::from_vec(k::gather(
707            v,
708            x.shape(),
709            &iv,
710            idx.shape(),
711            d,
712            slice_sizes
713        )));
714        Ok(vec![HostArray::from_buffer(b, shape)])
715    }
716
717    fn batch(
718        &'static self,
719        cx: &mut dyn BatchCx,
720        inputs: &[Batched],
721        params: &Params,
722    ) -> Result<Vec<Batched>> {
723        batch_gather(cx, &inputs[0], &inputs[1], params)
724    }
725
726    fn lower(
727        &self,
728        cx: &mut dyn LowerCx,
729        inputs: &[HloValue],
730        params: &Params,
731        outputs: &[AVal],
732    ) -> Result<Vec<HloValue>> {
733        let Params::Gather {
734            dimension_numbers: d,
735            slice_sizes,
736            indices_are_sorted,
737            ..
738        } = params
739        else {
740            return Err(wrong_params(self.name()));
741        };
742        let out = &outputs[0];
743        // An empty result needs no indexing, as in JAX.
744        if out.shape.size() == 0 {
745            return Ok(vec![cx.splat(Value::Int(0), out)]);
746        }
747        // XLA clamps the start indices, which is the `Clip` mode.
748        let q = inputs[1].aval.shape.rank();
749        let attrs = format!(
750            "dimension_numbers = #stablehlo.gather<{}>, indices_are_sorted = \
751             {indices_are_sorted}, slice_sizes = {}",
752            dims_attr(
753                &[
754                    ("offset_dims", &d.offset_dims),
755                    ("collapsed_slice_dims", &d.collapsed_slice_dims),
756                    ("operand_batching_dims", &d.operand_batching_dims),
757                    (
758                        "start_indices_batching_dims",
759                        &d.start_indices_batching_dims
760                    ),
761                    ("start_index_map", &d.start_index_map),
762                ],
763                q - 1
764            ),
765            i64_array(slice_sizes)
766        );
767        Ok(vec![cx.op1("stablehlo.gather", inputs, &attrs, out)])
768    }
769
770    fn jvp(
771        &'static self,
772        cx: &mut dyn AdCx,
773        primals: &[Atom],
774        tangents: &[Tangent],
775        params: &Params,
776    ) -> Result<(Vec<Atom>, Vec<Tangent>)> {
777        iad::gather_jvp(cx, primals, tangents, params)
778    }
779
780    fn transpose(
781        &'static self,
782        cx: &mut dyn AdCx,
783        cotangents: &[Tangent],
784        inputs: &[TransposeInput],
785        params: &Params,
786    ) -> Result<Vec<Tangent>> {
787        iad::gather_transpose(cx, &cotangents[0], inputs, params)
788    }
789}
790
791/// A primitive of the scatter family.
792#[derive(Debug)]
793pub(crate) struct Scatter {
794    name: &'static str,
795    combine: Option<BinaryOp>,
796}
797
798/// Writes updates at run-time start indices ([`Params::Scatter`]). With
799/// repeated indices, which update wins is unspecified.
800pub static SCATTER: Prim = Prim::new(&Scatter {
801    name: "scatter",
802    combine: None,
803});
804/// Adds updates at run-time start indices.
805pub static SCATTER_ADD: Prim = Prim::new(&Scatter {
806    name: "scatter-add",
807    combine: Some(BinaryOp::Add),
808});
809/// Multiplies by updates at run-time start indices.
810pub static SCATTER_MUL: Prim = Prim::new(&Scatter {
811    name: "scatter-mul",
812    combine: Some(BinaryOp::Mul),
813});
814/// Takes the minimum with updates at run-time start indices.
815pub static SCATTER_MIN: Prim = Prim::new(&Scatter {
816    name: "scatter-min",
817    combine: Some(BinaryOp::Min),
818});
819/// Takes the maximum with updates at run-time start indices.
820pub static SCATTER_MAX: Prim = Prim::new(&Scatter {
821    name: "scatter-max",
822    combine: Some(BinaryOp::Max),
823});
824
825fn scatter_check(
826    name: &'static str,
827    x: &AVal,
828    idx: &AVal,
829    u: &AVal,
830    d: &ScatterDims,
831) -> Result<()> {
832    let r = x.shape.rank();
833    let q = check_indices(name, idx, d.scatter_dims_to_operand_dims.len())?;
834    if u.dtype != x.dtype || u.shape.rank() != d.update_window_dims.len() + q - 1 {
835        return Err(Error::type_error(
836            name,
837            format!("invalid updates {u} for {x} and {idx}"),
838        ));
839    }
840    sorted_unique(
841        name,
842        "update_window_dims",
843        &d.update_window_dims,
844        u.shape.rank(),
845    )?;
846    sorted_unique(name, "inserted_window_dims", &d.inserted_window_dims, r)?;
847    sorted_unique(name, "operand_batching_dims", &d.operand_batching_dims, r)?;
848    let windowed = r - d.inserted_window_dims.len() - d.operand_batching_dims.len();
849    let ok = windowed == d.update_window_dims.len()
850        && d.scatter_dims_to_operand_dims
851            .iter()
852            .all(|m| *m < r && !d.operand_batching_dims.contains(m))
853        && d.inserted_window_dims
854            .iter()
855            .all(|i| !d.operand_batching_dims.contains(i))
856        && d.scatter_indices_batching_dims.len() == d.operand_batching_dims.len()
857        && d.scatter_indices_batching_dims.iter().all(|&b| b < q - 1)
858        && d.operand_batching_dims
859            .iter()
860            .zip(&d.scatter_indices_batching_dims)
861            .all(|(&o, &i)| x.shape[o] == idx.shape[i]);
862    if !ok {
863        return Err(Error::type_error(
864            name,
865            format!("invalid dimension numbers {d:?}"),
866        ));
867    }
868    let window = k::scatter_window(r, &u.shape, d);
869    if window.iter().zip(x.shape.dims()).any(|(w, n)| w > n) {
870        return Err(Error::type_error(
871            name,
872            format!("the update window of {u} does not fit {x}"),
873        ));
874    }
875    let scatter_dims: Vec<usize> = (0..u.shape.rank())
876        .filter(|i| !d.update_window_dims.contains(i))
877        .collect();
878    if scatter_dims
879        .iter()
880        .enumerate()
881        .any(|(k, &sd)| u.shape[sd] != idx.shape[k])
882    {
883        return Err(Error::type_error(
884            name,
885            format!("the scatter dimensions of {u} must match {idx}"),
886        ));
887    }
888    Ok(())
889}
890
891impl Primitive for Scatter {
892    fn name(&self) -> &'static str {
893        self.name
894    }
895    fn abstract_eval(&self, inputs: &[AVal], params: &Params) -> Result<Vec<AVal>> {
896        arity(self.name, inputs, 3)?;
897        let Params::Scatter {
898            dimension_numbers, ..
899        } = params
900        else {
901            return Err(wrong_params(self.name));
902        };
903        let x = &inputs[0];
904        if let Some(op) = self.combine
905            && (!op.supports(x.dtype) || x.dtype == DType::Bool)
906        {
907            return Err(Error::type_error(
908                self.name,
909                format!("does not accept {} operands", x.dtype),
910            ));
911        }
912        scatter_check(self.name, x, &inputs[1], &inputs[2], dimension_numbers)?;
913        Ok(vec![x.clone()])
914    }
915    fn eval(
916        &self,
917        _: &dyn EvalCx,
918        inputs: &[HostArray],
919        params: &Params,
920    ) -> Result<Vec<HostArray>> {
921        let Params::Scatter {
922            dimension_numbers: d,
923            mode,
924            ..
925        } = params
926        else {
927            return Err(wrong_params(self.name));
928        };
929        let (x, idx, u) = (&inputs[0], &inputs[1], &inputs[2]);
930        let iv = indices(idx);
931        let b = with_buffer!(x.buffer(), |v| Buffer::from_vec(scatter_typed(
932            v,
933            x,
934            &iv,
935            idx,
936            u,
937            d,
938            *mode,
939            self.combine
940        )));
941        Ok(vec![HostArray::from_buffer(b, x.shape().clone())])
942    }
943
944    fn batch(
945        &'static self,
946        cx: &mut dyn BatchCx,
947        inputs: &[Batched],
948        params: &Params,
949    ) -> Result<Vec<Batched>> {
950        batch_scatter(cx, Prim::new(self), inputs, params)
951    }
952
953    fn lower(
954        &self,
955        cx: &mut dyn LowerCx,
956        inputs: &[HloValue],
957        params: &Params,
958        outputs: &[AVal],
959    ) -> Result<Vec<HloValue>> {
960        let Params::Scatter {
961            dimension_numbers: d,
962            mode,
963            indices_are_sorted,
964            unique_indices,
965        } = params
966        else {
967            return Err(wrong_params(self.name));
968        };
969        let (operand, updates) = (&inputs[0], &inputs[2]);
970        let mut indices = inputs[1].clone();
971        let q = indices.aval.shape.rank();
972        if *mode == GatherScatterMode::Clip {
973            // XLA drops out-of-bounds windows, so clipping clamps the indices
974            // first, as JAX does.
975            let rank = operand.aval.shape.rank();
976            let window = k::scatter_window(rank, &updates.aval.shape, d);
977            let dtype = indices.aval.dtype;
978            let bounds: Vec<i64> = d
979                .scatter_dims_to_operand_dims
980                .iter()
981                .map(|&od| (operand.aval.shape[od] - window[od]) as i64)
982                .collect();
983            let n = bounds.len();
984            let bounds = cx.constant(&HostArray::from_vec(bounds, [n]).convert(dtype));
985            let bounds = cx.op1(
986                "stablehlo.broadcast_in_dim",
987                &[bounds],
988                &format!("broadcast_dimensions = array<i64: {}>", q - 1),
989                &indices.aval,
990            );
991            let zero = cx.splat(Value::Int(0), &AVal::scalar(dtype));
992            let aval = indices.aval.clone();
993            indices = cx.op1("stablehlo.clamp", &[zero, indices, bounds], "", &aval);
994        }
995        let scalar = AVal::scalar(operand.aval.dtype);
996        let combine = self.combine;
997        let mut body = |cx: &mut dyn LowerCx, args: &[HloValue]| {
998            let (x, y) = (&args[0], &args[1]);
999            Ok(vec![match combine {
1000                None => y.clone(),
1001                Some(BinaryOp::Max) => cx.min_max("stablehlo.maximum", x, y, &scalar),
1002                Some(BinaryOp::Min) => cx.min_max("stablehlo.minimum", x, y, &scalar),
1003                Some(BinaryOp::Mul) => cx.op1("stablehlo.multiply", args, "", &scalar),
1004                Some(_) => cx.op1("stablehlo.add", args, "", &scalar),
1005            }])
1006        };
1007        let mut regions = [Region {
1008            args: vec![
1009                AVal::scalar(operand.aval.dtype),
1010                AVal::scalar(operand.aval.dtype),
1011            ],
1012            body: &mut body,
1013        }];
1014        let attrs = format!(
1015            "indices_are_sorted = {indices_are_sorted}, scatter_dimension_numbers = \
1016             #stablehlo.scatter<{}>, unique_indices = {unique_indices}",
1017            dims_attr(
1018                &[
1019                    ("update_window_dims", &d.update_window_dims),
1020                    ("inserted_window_dims", &d.inserted_window_dims),
1021                    ("input_batching_dims", &d.operand_batching_dims),
1022                    (
1023                        "scatter_indices_batching_dims",
1024                        &d.scatter_indices_batching_dims
1025                    ),
1026                    (
1027                        "scatter_dims_to_operand_dims",
1028                        &d.scatter_dims_to_operand_dims
1029                    ),
1030                ],
1031                q - 1
1032            )
1033        );
1034        cx.op_with_regions(
1035            "stablehlo.scatter",
1036            &[operand.clone(), indices, updates.clone()],
1037            &attrs,
1038            &mut regions,
1039            outputs,
1040        )
1041    }
1042
1043    fn jvp(
1044        &'static self,
1045        cx: &mut dyn AdCx,
1046        primals: &[Atom],
1047        tangents: &[Tangent],
1048        params: &Params,
1049    ) -> Result<(Vec<Atom>, Vec<Tangent>)> {
1050        match self.combine {
1051            None => iad::scatter_jvp(cx, primals, tangents, params),
1052            Some(BinaryOp::Add) => iad::scatter_add_jvp(cx, primals, tangents, params),
1053            Some(BinaryOp::Mul) => iad::scatter_mul_jvp(cx, primals, tangents, params),
1054            Some(_) => iad::scatter_extremal_jvp(cx, Prim::new(self), primals, tangents, params),
1055        }
1056    }
1057
1058    fn transpose(
1059        &'static self,
1060        cx: &mut dyn AdCx,
1061        cotangents: &[Tangent],
1062        inputs: &[TransposeInput],
1063        params: &Params,
1064    ) -> Result<Vec<Tangent>> {
1065        match self.combine {
1066            None => iad::scatter_transpose(cx, &cotangents[0], inputs, params),
1067            Some(BinaryOp::Add) => iad::scatter_add_transpose(cx, &cotangents[0], inputs, params),
1068            Some(BinaryOp::Mul) => iad::scatter_mul_transpose(cx, &cotangents[0], inputs, params),
1069            Some(_) => Err(Error::unsupported(self.name, "not linear")),
1070        }
1071    }
1072}
1073
1074// The operands and the dimension numbers of a scatter, unpacked.
1075#[allow(clippy::too_many_arguments)]
1076fn scatter_typed<T: Element>(
1077    v: &[T],
1078    x: &HostArray,
1079    iv: &[i64],
1080    idx: &HostArray,
1081    u: &HostArray,
1082    d: &ScatterDims,
1083    mode: ruxla_ir::GatherScatterMode,
1084    combine: Option<BinaryOp>,
1085) -> Vec<T> {
1086    let f = combine.map(|op| move |a: T, b: T| T::binary(op, a, b));
1087    let f_ref: Option<&dyn Fn(T, T) -> T> = f.as_ref().map(|f| f as &dyn Fn(T, T) -> T);
1088    k::scatter(
1089        v,
1090        x.shape(),
1091        iv,
1092        idx.shape(),
1093        u.as_slice().expect("same types"),
1094        u.shape(),
1095        d,
1096        mode,
1097        f_ref,
1098    )
1099}
1100
1101/// The identity of a reduction as a scalar: zero, or the lowest or highest
1102/// value.
1103fn identity(op: ReduceOp, dtype: DType) -> HostArray {
1104    with_dtype!(dtype, |T| HostArray::from_vec(
1105        vec![match op {
1106            ReduceOp::Sum => T::from_value(Value::Int(0)),
1107            ReduceOp::Max => <T as Ops>::lowest(),
1108            ReduceOp::Min => <T as Ops>::highest(),
1109        }],
1110        Shape::scalar()
1111    ))
1112}
1113
1114/// Formats gather or scatter dimension numbers, leaving out empty fields.
1115fn dims_attr(fields: &[(&str, &[usize])], index_vector_dim: usize) -> String {
1116    let mut parts: Vec<String> = fields
1117        .iter()
1118        .filter(|(_, v)| !v.is_empty())
1119        .map(|(k, v)| {
1120            let items: Vec<String> = v.iter().map(ToString::to_string).collect();
1121            format!("{k} = [{}]", items.join(", "))
1122        })
1123        .collect();
1124    parts.push(format!("index_vector_dim = {index_vector_dim}"));
1125    parts.join(", ")
1126}
1127
1128fn shift(dims: &[usize]) -> Vec<usize> {
1129    dims.iter().map(|d| d + 1).collect()
1130}
1131
1132/// The batching rule of `gather`, as JAX's `_gather_batching_rule`.
1133pub(crate) fn batch_gather(
1134    cx: &mut dyn BatchCx,
1135    operand: &Batched,
1136    indices: &Batched,
1137    params: &Params,
1138) -> Result<Vec<Batched>> {
1139    let Params::Gather {
1140        dimension_numbers: d,
1141        slice_sizes,
1142        mode,
1143        indices_are_sorted,
1144        unique_indices,
1145    } = params
1146    else {
1147        return Err(wrong_params("gather"));
1148    };
1149    let n = cx.axis_size();
1150    let (atoms, dims, sizes, sorted, unique) = match (operand.bdim, indices.bdim) {
1151        // The batch is one more sliced dimension of the operand.
1152        (Some(_), None) => {
1153            let dims = GatherDims {
1154                offset_dims: [vec![0], shift(&d.offset_dims)].concat(),
1155                collapsed_slice_dims: shift(&d.collapsed_slice_dims),
1156                start_index_map: shift(&d.start_index_map),
1157                operand_batching_dims: shift(&d.operand_batching_dims),
1158                start_indices_batching_dims: d.start_indices_batching_dims.clone(),
1159            };
1160            let atoms = [bdim_at_front(cx, operand)?, indices.atom.clone()];
1161            (
1162                atoms,
1163                dims,
1164                batching::insert_dim(slice_sizes, 0, n),
1165                *indices_are_sorted,
1166                *unique_indices,
1167            )
1168        }
1169        // The batch is one more batch dimension of the indices.
1170        (None, Some(_)) => {
1171            let dims = GatherDims {
1172                offset_dims: shift(&d.offset_dims),
1173                start_indices_batching_dims: shift(&d.start_indices_batching_dims),
1174                ..d.clone()
1175            };
1176            let atoms = [operand.atom.clone(), bdim_at_front(cx, indices)?];
1177            // Batching indexed accesses into the same array may break the
1178            // order and uniqueness of the indices.
1179            (atoms, dims, slice_sizes.clone(), false, false)
1180        }
1181        // Both batched: a batching dimension of both.
1182        (Some(_), Some(_)) => {
1183            let dims = GatherDims {
1184                offset_dims: shift(&d.offset_dims),
1185                collapsed_slice_dims: shift(&d.collapsed_slice_dims),
1186                start_index_map: shift(&d.start_index_map),
1187                operand_batching_dims: [vec![0], shift(&d.operand_batching_dims)].concat(),
1188                start_indices_batching_dims: [vec![0], shift(&d.start_indices_batching_dims)]
1189                    .concat(),
1190            };
1191            let atoms = [bdim_at_front(cx, operand)?, bdim_at_front(cx, indices)?];
1192            // A slice of size 1 cannot be taken from a dimension of size 0.
1193            let first = if n == 0 { 0 } else { 1 };
1194            (
1195                atoms,
1196                dims,
1197                batching::insert_dim(slice_sizes, 0, first),
1198                *indices_are_sorted,
1199                *unique_indices,
1200            )
1201        }
1202        (None, None) => {
1203            return Err(Error::Malformed(String::from(
1204                "the batching rule of gather was called without batched operands",
1205            )));
1206        }
1207    };
1208    let out = batching::bind1(
1209        cx,
1210        GATHER,
1211        &atoms,
1212        Params::Gather {
1213            dimension_numbers: dims,
1214            slice_sizes: sizes,
1215            mode: *mode,
1216            indices_are_sorted: sorted,
1217            unique_indices: unique,
1218        },
1219    )?;
1220    Ok(vec![Batched::mapped(out, 0)])
1221}
1222
1223/// The batching rule of the scatter family, as JAX's
1224/// `_scatter_batching_rule`.
1225pub(crate) fn batch_scatter(
1226    cx: &mut dyn BatchCx,
1227    prim: Prim,
1228    inputs: &[Batched],
1229    params: &Params,
1230) -> Result<Vec<Batched>> {
1231    let Params::Scatter {
1232        dimension_numbers: d,
1233        mode,
1234        indices_are_sorted,
1235        unique_indices,
1236    } = params
1237    else {
1238        return Err(wrong_params(prim.name()));
1239    };
1240    let (operand, indices, updates) = (&inputs[0], &inputs[1], &inputs[2]);
1241    let operand_atom = bdim_at_front(cx, operand)?;
1242    let updates_atom = bdim_at_front(cx, updates)?;
1243    let (indices_atom, dims) = match indices.bdim {
1244        None => (
1245            indices.atom.clone(),
1246            ScatterDims {
1247                update_window_dims: [vec![0], shift(&d.update_window_dims)].concat(),
1248                inserted_window_dims: shift(&d.inserted_window_dims),
1249                scatter_dims_to_operand_dims: shift(&d.scatter_dims_to_operand_dims),
1250                operand_batching_dims: shift(&d.operand_batching_dims),
1251                scatter_indices_batching_dims: d.scatter_indices_batching_dims.clone(),
1252            },
1253        ),
1254        Some(_) => (
1255            bdim_at_front(cx, indices)?,
1256            ScatterDims {
1257                update_window_dims: shift(&d.update_window_dims),
1258                inserted_window_dims: shift(&d.inserted_window_dims),
1259                scatter_dims_to_operand_dims: shift(&d.scatter_dims_to_operand_dims),
1260                operand_batching_dims: [vec![0], shift(&d.operand_batching_dims)].concat(),
1261                scatter_indices_batching_dims: [vec![0], shift(&d.scatter_indices_batching_dims)]
1262                    .concat(),
1263            },
1264        ),
1265    };
1266    let out = batching::bind1(
1267        cx,
1268        prim,
1269        &[operand_atom, indices_atom, updates_atom],
1270        Params::Scatter {
1271            dimension_numbers: dims,
1272            mode: *mode,
1273            indices_are_sorted: *indices_are_sorted,
1274            unique_indices: *unique_indices,
1275        },
1276    )?;
1277    Ok(vec![Batched::mapped(out, 0)])
1278}
1279
1280/// Stacks the start indices of `dynamic_slice` or `dynamic_update_slice`
1281/// into an index array of shape `[n, k]` (batched at 0) or `[k]`, as JAX's
1282/// `_batch_dynamic_slice_indices` does.
1283fn batch_dynamic_slice_indices(cx: &mut dyn BatchCx, starts: &[Batched]) -> Result<Batched> {
1284    if starts.is_empty() {
1285        let empty = cx.constant(HostArray::from_vec(Vec::<i32>::new(), [0]));
1286        return Ok(Batched::unmapped(empty));
1287    }
1288    let n = cx.axis_size();
1289    let batched = starts.iter().any(|i| i.bdim.is_some());
1290    let parts = starts
1291        .iter()
1292        .map(|i| {
1293            let (shape, dims) = match (batched, i.bdim) {
1294                (false, _) => (vec![1], vec![]),
1295                (true, None) => (vec![n, 1], vec![]),
1296                (true, Some(_)) => (vec![n, 1], vec![0]),
1297            };
1298            batching::bind1(
1299                cx,
1300                crate::structural::BROADCAST_IN_DIM,
1301                std::slice::from_ref(&i.atom),
1302                Params::BroadcastInDim {
1303                    shape: shape.into(),
1304                    broadcast_dimensions: dims,
1305                },
1306            )
1307        })
1308        .collect::<Result<Vec<_>>>()?;
1309    let index = batching::bind1(
1310        cx,
1311        crate::structural::CONCATENATE,
1312        &parts,
1313        Params::Concatenate {
1314            dimension: usize::from(batched),
1315        },
1316    )?;
1317    Ok(if batched {
1318        Batched::mapped(index, 0)
1319    } else {
1320        Batched::unmapped(index)
1321    })
1322}
1323
1324/// The batching rule of `dynamic_slice`: a gather, as in JAX.
1325pub(crate) fn batch_dynamic_slice(
1326    cx: &mut dyn BatchCx,
1327    operand: &Batched,
1328    starts: &[Batched],
1329    slice_sizes: &[usize],
1330) -> Result<Vec<Batched>> {
1331    let dims: Vec<usize> = (0..starts.len()).collect();
1332    let d = GatherDims {
1333        offset_dims: dims.clone(),
1334        collapsed_slice_dims: vec![],
1335        start_index_map: dims,
1336        operand_batching_dims: vec![],
1337        start_indices_batching_dims: vec![],
1338    };
1339    let index = batch_dynamic_slice_indices(cx, starts)?;
1340    // XLA's gather clamps the start indices like `dynamic_slice`.
1341    let params = Params::Gather {
1342        dimension_numbers: d,
1343        slice_sizes: slice_sizes.to_vec(),
1344        mode: GatherScatterMode::PromiseInBounds,
1345        indices_are_sorted: true,
1346        unique_indices: true,
1347    };
1348    batch_gather(cx, operand, &index, &params)
1349}
1350
1351/// The batching rule of `dynamic_update_slice`: a scatter, as in JAX.
1352pub(crate) fn batch_dynamic_update_slice(
1353    cx: &mut dyn BatchCx,
1354    operand: &Batched,
1355    update: &Batched,
1356    starts: &[Batched],
1357) -> Result<Vec<Batched>> {
1358    let dims: Vec<usize> = (0..starts.len()).collect();
1359    let d = ScatterDims {
1360        update_window_dims: dims.clone(),
1361        inserted_window_dims: vec![],
1362        scatter_dims_to_operand_dims: dims,
1363        operand_batching_dims: vec![],
1364        scatter_indices_batching_dims: vec![],
1365    };
1366    let index = batch_dynamic_slice_indices(cx, starts)?;
1367    let params = Params::Scatter {
1368        dimension_numbers: d,
1369        mode: GatherScatterMode::Clip,
1370        indices_are_sorted: true,
1371        unique_indices: true,
1372    };
1373    batch_scatter(
1374        cx,
1375        SCATTER,
1376        &[operand.clone(), index, update.clone()],
1377        &params,
1378    )
1379}