Skip to main content

ruxla_prims/
cumulative.rs

1//! Cumulative reductions, following JAX's `lax.cumsum_p`, `cumprod_p`,
2//! `cummax_p`, `cummin_p`, and `cumlogsumexp_p`.
3
4use ruxla_ir::Atom;
5use ruxla_ir::ad::{AdCx, Tangent, TransposeInput};
6use ruxla_ir::batching::{BatchCx, Batched};
7use ruxla_ir::lowering::{HloValue, LowerCx, Region, i64_array};
8use ruxla_ir::{AVal, DType, Error, EvalCx, HostArray, Params, Prim, Primitive, Result, Value};
9use ruxla_kernels::array::{self as k, CumulativeOp};
10use ruxla_kernels::{Buffer, with_buffer, with_dtype};
11
12use crate::ad::{add_tangents, bind1, full, mul_tangent};
13use crate::batching::{self, batched_operand};
14use crate::elementwise::{ABS, ADD, EQ, EXP, LOG1P, MAX, MIN, MUL, NE, NEG, OR, SELECT_N, SUB};
15use crate::structural::{CONCATENATE, PAD, REV, SLICE};
16use crate::structural_ad as sad;
17use crate::util::{arity, wrong_params};
18
19/// A cumulative reduction.
20#[derive(Debug)]
21pub(crate) struct Cumulative {
22    name: &'static str,
23    op: CumulativeOp,
24}
25
26/// The cumulative sum along an axis ([`Params::Cumulative`]).
27pub static CUMSUM: Prim = Prim::new(&Cumulative {
28    name: "cumsum",
29    op: CumulativeOp::Sum,
30});
31/// The cumulative product along an axis.
32pub static CUMPROD: Prim = Prim::new(&Cumulative {
33    name: "cumprod",
34    op: CumulativeOp::Prod,
35});
36/// The cumulative maximum along an axis, propagating NaN.
37pub static CUMMAX: Prim = Prim::new(&Cumulative {
38    name: "cummax",
39    op: CumulativeOp::Max,
40});
41/// The cumulative minimum along an axis, propagating NaN.
42pub static CUMMIN: Prim = Prim::new(&Cumulative {
43    name: "cummin",
44    op: CumulativeOp::Min,
45});
46/// The cumulative `logsumexp` along an axis (floats only).
47pub static CUMLOGSUMEXP: Prim = Prim::new(&Cumulative {
48    name: "cumlogsumexp",
49    op: CumulativeOp::LogSumExp,
50});
51
52fn cumulative_params(name: &'static str, params: &Params) -> Result<(usize, bool)> {
53    match *params {
54        Params::Cumulative { axis, reverse } => Ok((axis, reverse)),
55        _ => Err(wrong_params(name)),
56    }
57}
58
59/// The identity of an operation as a scalar.
60fn identity(op: CumulativeOp, dtype: DType) -> HostArray {
61    with_dtype!(dtype, |T| HostArray::from_vec(
62        vec![op.identity::<T>()],
63        ruxla_ir::Shape::scalar()
64    ))
65}
66
67/// `stablehlo.compare NE` of floats (NaN test of `x - y`).
68fn is_nan(cx: &mut dyn LowerCx, x: &HloValue) -> HloValue {
69    cx.op1(
70        "stablehlo.compare",
71        &[x.clone(), x.clone()],
72        "comparison_direction = #stablehlo<comparison_direction NE>, \
73         compare_type = #stablehlo<comparison_type FLOAT>",
74        &AVal::new(x.aval.shape.clone(), DType::Bool),
75    )
76}
77
78impl Primitive for Cumulative {
79    fn name(&self) -> &'static str {
80        self.name
81    }
82
83    fn abstract_eval(&self, inputs: &[AVal], params: &Params) -> Result<Vec<AVal>> {
84        arity(self.name, inputs, 1)?;
85        let (axis, _) = cumulative_params(self.name, params)?;
86        let x = &inputs[0];
87        let accepted = match self.op {
88            CumulativeOp::LogSumExp => x.dtype.is_float(),
89            // Complex numbers are not ordered for XLA's reductions.
90            CumulativeOp::Max | CumulativeOp::Min => {
91                x.dtype != DType::Bool && !x.dtype.is_complex()
92            }
93            _ => x.dtype != DType::Bool,
94        };
95        if !accepted {
96            return Err(Error::type_error(
97                self.name,
98                format!("does not accept {} operands", x.dtype),
99            ));
100        }
101        if axis >= x.shape.rank() {
102            return Err(Error::type_error(
103                self.name,
104                format!("axis {axis} is out of bounds for {x}"),
105            ));
106        }
107        Ok(vec![x.clone()])
108    }
109
110    fn eval(
111        &self,
112        _: &dyn EvalCx,
113        inputs: &[HostArray],
114        params: &Params,
115    ) -> Result<Vec<HostArray>> {
116        let (axis, reverse) = cumulative_params(self.name, params)?;
117        let x = &inputs[0];
118        let b = with_buffer!(x.buffer(), |v| Buffer::from_vec(k::cumulative(
119            v,
120            x.shape(),
121            axis,
122            reverse,
123            self.op
124        )));
125        Ok(vec![HostArray::from_buffer(b, x.shape().clone())])
126    }
127
128    /// JAX's `_cumred_batch_rule`.
129    fn batch(
130        &'static self,
131        cx: &mut dyn BatchCx,
132        inputs: &[Batched],
133        params: &Params,
134    ) -> Result<Vec<Batched>> {
135        let (axis, reverse) = cumulative_params(self.name, params)?;
136        let x = &inputs[0];
137        let b = batched_operand(self.name, x)?;
138        let out = batching::bind1(
139            cx,
140            Prim::new(self),
141            std::slice::from_ref(&x.atom),
142            Params::Cumulative {
143                axis: batching::batched_dim(axis, b),
144                reverse,
145            },
146        )?;
147        Ok(vec![Batched::mapped(out, b)])
148    }
149
150    /// JAX's lowering on CPU (`cumred_reduce_window_impl`): a
151    /// `reduce_window` whose window spans the axis, padded before it (or
152    /// after it, in reverse).
153    fn lower(
154        &self,
155        cx: &mut dyn LowerCx,
156        inputs: &[HloValue],
157        params: &Params,
158        outputs: &[AVal],
159    ) -> Result<Vec<HloValue>> {
160        let (axis, reverse) = cumulative_params(self.name, params)?;
161        let x = &inputs[0];
162        let shape = x.aval.shape.clone();
163        let n = shape[axis];
164        if n == 0 {
165            return Ok(vec![x.clone()]);
166        }
167        let dtype = x.aval.dtype;
168        let scalar = AVal::scalar(dtype);
169        let mut init = cx.constant(&identity(self.op, dtype));
170        // `reduce_window_sum`, `_max`, and `_min` broadcast the initial value
171        // to its own (scalar) shape in JAX's lowering.
172        if matches!(
173            self.op,
174            CumulativeOp::Sum | CumulativeOp::Max | CumulativeOp::Min
175        ) {
176            init = cx.op1(
177                "stablehlo.broadcast_in_dim",
178                &[init],
179                "broadcast_dimensions = array<i64>",
180                &scalar,
181            );
182        }
183        let op = self.op;
184        let mut body = |cx: &mut dyn LowerCx, args: &[HloValue]| {
185            let (a, b) = (&args[0], &args[1]);
186            Ok(vec![match op {
187                CumulativeOp::Sum => cx.op1("stablehlo.add", args, "", &scalar),
188                CumulativeOp::Prod => cx.op1("stablehlo.multiply", args, "", &scalar),
189                CumulativeOp::Max => cx.min_max("stablehlo.maximum", a, b, &scalar),
190                CumulativeOp::Min => cx.min_max("stablehlo.minimum", a, b, &scalar),
191                CumulativeOp::LogSumExp => {
192                    // JAX's `logaddexp`. NaNs reach the result through the
193                    // `select` whether or not `maximum` propagates them.
194                    let amax = cx.op1("stablehlo.maximum", args, "", &scalar);
195                    let delta = cx.op1("stablehlo.subtract", args, "", &scalar);
196                    let nan = is_nan(cx, &delta);
197                    let sum = cx.op1("stablehlo.add", args, "", &scalar);
198                    let abs = cx.op1("stablehlo.abs", &[delta], "", &scalar);
199                    let neg = cx.op1("stablehlo.negate", &[abs], "", &scalar);
200                    let exp = cx.op1("stablehlo.exponential", &[neg], "", &scalar);
201                    let log = cx.op1("stablehlo.log_plus_one", &[exp], "", &scalar);
202                    let r = cx.op1("stablehlo.add", &[amax, log], "", &scalar);
203                    cx.op1("stablehlo.select", &[nan, sum, r], "", &scalar)
204                }
205            }])
206        };
207        let mut regions = [Region {
208            args: vec![scalar.clone(), scalar.clone()],
209            body: &mut body,
210        }];
211        let rank = shape.rank();
212        let mut window = vec![1; rank];
213        window[axis] = n;
214        let padding: Vec<String> = (0..rank)
215            .map(|d| match d {
216                d if d != axis => String::from("[0, 0]"),
217                _ if reverse => format!("[0, {}]", n - 1),
218                _ => format!("[{}, 0]", n - 1),
219            })
220            .collect();
221        let ones = vec![1; rank];
222        let attrs = format!(
223            "base_dilations = {ones}, padding = dense<[{padding}]> : tensor<{rank}x2xi64>, \
224             window_dilations = {ones}, window_dimensions = {window}, window_strides = {ones}",
225            ones = i64_array(&ones),
226            padding = padding.join(", "),
227            window = i64_array(&window),
228        );
229        cx.op_with_regions(
230            "stablehlo.reduce_window",
231            &[x.clone(), init],
232            &attrs,
233            &mut regions,
234            outputs,
235        )
236    }
237
238    /// `cumsum` is linear (JAX's `deflinear2`). The others differentiate,
239    /// as JAX's `_cumulative_jvp_rule` does, the parallel prefix scan
240    /// (`associative_scan`) of their operation.
241    fn jvp(
242        &'static self,
243        cx: &mut dyn AdCx,
244        primals: &[Atom],
245        tangents: &[Tangent],
246        params: &Params,
247    ) -> Result<(Vec<Atom>, Vec<Tangent>)> {
248        if self.op == CumulativeOp::Sum {
249            return sad::linear_jvp(cx, Prim::new(self), primals, tangents, params);
250        }
251        let (axis, reverse) = cumulative_params(self.name, params)?;
252        let x = Dual {
253            p: primals[0].clone(),
254            t: tangents[0].clone(),
255        };
256        let out = associative_scan(cx, self.op, x, axis, reverse)?;
257        Ok((vec![out.p], vec![out.t]))
258    }
259
260    /// JAX's `_cumsum_transpose_rule`: the cumulative sum in the other
261    /// direction.
262    fn transpose(
263        &'static self,
264        cx: &mut dyn AdCx,
265        cotangents: &[Tangent],
266        inputs: &[TransposeInput],
267        params: &Params,
268    ) -> Result<Vec<Tangent>> {
269        let _ = inputs;
270        if self.op != CumulativeOp::Sum {
271            return Err(Error::unsupported(self.name, "not linear"));
272        }
273        let (axis, reverse) = cumulative_params(self.name, params)?;
274        let ct = cotangents[0]
275            .as_ref()
276            .map(|ct| {
277                bind1(
278                    cx,
279                    CUMSUM,
280                    std::slice::from_ref(ct),
281                    Params::Cumulative {
282                        axis,
283                        reverse: !reverse,
284                    },
285                )
286            })
287            .transpose()?;
288        Ok(vec![ct])
289    }
290}
291
292/// A primal value with its tangent, for differentiating a composition of
293/// primitives by applying their JVP rules (as `jax.jvp` traces a function).
294#[derive(Clone)]
295struct Dual {
296    p: Atom,
297    t: Tangent,
298}
299
300impl Dual {
301    fn constant(p: Atom) -> Self {
302        Self { p, t: None }
303    }
304}
305
306/// Applies a primitive to duals with its JVP rule (or just binds it when
307/// every tangent is zero).
308fn apply(cx: &mut dyn AdCx, prim: Prim, inputs: &[Dual], params: Params) -> Result<Vec<Dual>> {
309    let primals: Vec<Atom> = inputs.iter().map(|d| d.p.clone()).collect();
310    let tangents: Vec<Tangent> = inputs.iter().map(|d| d.t.clone()).collect();
311    if tangents.iter().all(Option::is_none) {
312        let outs = cx.bind(prim, &primals, params)?;
313        return Ok(outs.into_iter().map(Dual::constant).collect());
314    }
315    let (ps, ts) = prim.jvp(cx, &primals, &tangents, &params)?;
316    Ok(ps.into_iter().zip(ts).map(|(p, t)| Dual { p, t }).collect())
317}
318
319fn apply1(cx: &mut dyn AdCx, prim: Prim, inputs: &[Dual], params: Params) -> Result<Dual> {
320    let mut outs = apply(cx, prim, inputs, params)?;
321    Ok(outs.remove(0))
322}
323
324/// JAX's `slicing.slice_in_dim`.
325fn slice_in_dim(
326    cx: &mut dyn AdCx,
327    x: &Dual,
328    start: usize,
329    limit: usize,
330    stride: usize,
331    axis: usize,
332) -> Result<Dual> {
333    let shape = x.p.aval().shape;
334    let rank = shape.rank();
335    let mut start_indices = vec![0; rank];
336    let mut limit_indices = shape.dims().to_vec();
337    let mut strides = vec![1; rank];
338    start_indices[axis] = start;
339    limit_indices[axis] = limit;
340    strides[axis] = stride;
341    apply1(
342        cx,
343        SLICE,
344        std::slice::from_ref(x),
345        Params::Slice {
346            start_indices,
347            limit_indices,
348            strides,
349        },
350    )
351}
352
353/// A scalar zero (or `false`) of a type, as JAX's `lax._const(x, 0)`.
354fn zero_literal(dtype: DType) -> Dual {
355    Dual::constant(crate::ad::scalar(dtype, Value::Int(0)))
356}
357
358/// JAX's `_interleave`: `a` at even positions and `b` at odd positions.
359fn interleave(cx: &mut dyn AdCx, a: &Dual, b: &Dual, axis: usize) -> Result<Dual> {
360    let (na, nb) = (a.p.aval().shape[axis], b.p.aval().shape[axis]);
361    let rank = a.p.aval().shape.rank();
362    let dtype = a.p.aval().dtype;
363    let mut a_pad = vec![(0, 0, 0); rank];
364    let mut b_pad = vec![(0, 0, 0); rank];
365    a_pad[axis] = (0, i64::from(na == nb), 1);
366    b_pad[axis] = (1, i64::from(na != nb), 1);
367    let zero = zero_literal(dtype);
368    let a = apply1(
369        cx,
370        PAD,
371        &[a.clone(), zero.clone()],
372        Params::Pad {
373            padding_config: a_pad,
374        },
375    )?;
376    let b = apply1(
377        cx,
378        PAD,
379        &[b.clone(), zero],
380        Params::Pad {
381            padding_config: b_pad,
382        },
383    )?;
384    let op = if dtype == DType::Bool { OR } else { ADD };
385    apply1(cx, op, &[a, b], Params::None)
386}
387
388/// JAX's `_replace_inf`: `x` with `inf` replaced by zero.
389fn replace_inf(cx: &mut dyn AdCx, x: &Atom) -> Result<Atom> {
390    let aval = x.aval();
391    let inf = full(cx, &aval, Value::Float(f64::INFINITY))?;
392    let is_inf = bind1(cx, EQ, &[x.clone(), inf], Params::None)?;
393    let zeros = full(cx, &aval, Value::Int(0))?;
394    bind1(cx, SELECT_N, &[is_inf, x.clone(), zeros], Params::None)
395}
396
397/// JAX's `logaddexp` (in `jax._src.lax.other`) with its custom JVP rule.
398fn logaddexp(cx: &mut dyn AdCx, a: &Dual, b: &Dual) -> Result<Dual> {
399    let (x1, x2) = (&a.p, &b.p);
400    let bin = |cx: &mut dyn AdCx, prim: Prim, x: &Atom, y: &Atom| {
401        bind1(cx, prim, &[x.clone(), y.clone()], Params::None)
402    };
403    let un = |cx: &mut dyn AdCx, prim: Prim, x: &Atom| {
404        bind1(cx, prim, std::slice::from_ref(x), Params::None)
405    };
406    let amax = bin(cx, MAX, x1, x2)?;
407    let delta = bin(cx, SUB, x1, x2)?;
408    let delta_nan = bin(cx, NE, &delta, &delta)?;
409    let sum = bin(cx, ADD, x1, x2)?;
410    let abs = un(cx, ABS, &delta)?;
411    let neg = un(cx, NEG, &abs)?;
412    let exp = un(cx, EXP, &neg)?;
413    let log = un(cx, LOG1P, &exp)?;
414    let r = bin(cx, ADD, &amax, &log)?;
415    let out = bind1(cx, SELECT_N, &[delta_nan, r, sum], Params::None)?;
416    if a.t.is_none() && b.t.is_none() {
417        return Ok(Dual::constant(out));
418    }
419    let out_finite = replace_inf(cx, &out)?;
420    let scale = |cx: &mut dyn AdCx, x: &Atom, t: &Tangent| -> Result<Tangent> {
421        if t.is_none() {
422            return Ok(None);
423        }
424        let x = replace_inf(cx, x)?;
425        let d = bin(cx, SUB, &x, &out_finite)?;
426        let e = un(cx, EXP, &d)?;
427        mul_tangent(cx, t, &e)
428    };
429    let t1 = scale(cx, x1, &a.t)?;
430    let t2 = scale(cx, x2, &b.t)?;
431    Ok(Dual {
432        p: out,
433        t: add_tangents(cx, t1, t2)?,
434    })
435}
436
437/// The combining function of a cumulative reduction, on duals.
438fn combine(cx: &mut dyn AdCx, op: CumulativeOp, a: &Dual, b: &Dual) -> Result<Dual> {
439    let prim = match op {
440        CumulativeOp::Sum => ADD,
441        CumulativeOp::Prod => MUL,
442        CumulativeOp::Max => MAX,
443        CumulativeOp::Min => MIN,
444        CumulativeOp::LogSumExp => return logaddexp(cx, a, b),
445    };
446    apply1(cx, prim, &[a.clone(), b.clone()], Params::None)
447}
448
449/// JAX's `lax.associative_scan` of one array, on duals.
450fn associative_scan(
451    cx: &mut dyn AdCx,
452    op: CumulativeOp,
453    x: Dual,
454    axis: usize,
455    reverse: bool,
456) -> Result<Dual> {
457    let rev = |cx: &mut dyn AdCx, x: &Dual| {
458        apply1(
459            cx,
460            REV,
461            std::slice::from_ref(x),
462            Params::Rev {
463                dimensions: vec![axis],
464            },
465        )
466    };
467    let x = if reverse { rev(cx, &x)? } else { x };
468    let scanned = scan(cx, op, &x, axis)?;
469    if reverse {
470        rev(cx, &scanned)
471    } else {
472        Ok(scanned)
473    }
474}
475
476/// `_scan` in JAX's `associative_scan`: combines adjacent pairs, scans
477/// them recursively (the elements at odd positions), and combines the
478/// results with the elements at even positions.
479fn scan(cx: &mut dyn AdCx, op: CumulativeOp, elems: &Dual, axis: usize) -> Result<Dual> {
480    let n = elems.p.aval().shape[axis];
481    if n < 2 {
482        return Ok(elems.clone());
483    }
484    let left = slice_in_dim(cx, elems, 0, n - 1, 2, axis)?;
485    let right = slice_in_dim(cx, elems, 1, n, 2, axis)?;
486    let reduced = combine(cx, op, &left, &right)?;
487    let odd = scan(cx, op, &reduced, axis)?;
488    let rest = slice_in_dim(cx, elems, 2, n, 2, axis)?;
489    let even = if n.is_multiple_of(2) {
490        let m = odd.p.aval().shape[axis];
491        let odd_init = slice_in_dim(cx, &odd, 0, m - 1, 1, axis)?;
492        combine(cx, op, &odd_init, &rest)?
493    } else {
494        combine(cx, op, &odd, &rest)?
495    };
496    let first = slice_in_dim(cx, elems, 0, 1, 1, axis)?;
497    let even = apply1(
498        cx,
499        CONCATENATE,
500        &[first, even],
501        Params::Concatenate { dimension: axis },
502    )?;
503    interleave(cx, &even, &odd, axis)
504}