Skip to main content

ruxla_prims/
batching.rs

1//! Helpers for batching rules (`vmap`), shared by the primitives and the
2//! `vmap` driver in `ruxla-transforms`.
3//!
4//! The rules follow JAX's batching rules, so that a function batched by
5//! ruxla compiles to the same program as one batched by JAX.
6
7use ruxla_ir::batching::{BatchCx, Batched};
8use ruxla_ir::{Atom, DType, Error, HostArray, Literal, Params, Prim, Result, Shape, Value};
9
10use crate::structural::{BROADCAST_IN_DIM, TRANSPOSE};
11
12/// Applies a primitive with one output.
13pub(crate) fn bind1(
14    cx: &mut dyn BatchCx,
15    prim: Prim,
16    inputs: &[Atom],
17    params: Params,
18) -> Result<Atom> {
19    let mut outputs = cx.bind(prim, inputs, params)?;
20    if outputs.len() != 1 {
21        return Err(Error::Malformed(format!(
22            "{} returned {} outputs, expected one",
23            prim.name(),
24            outputs.len()
25        )));
26    }
27    Ok(outputs.remove(0))
28}
29
30/// Returns `dims` with `size` inserted at position `at`.
31pub fn insert_dim(dims: &[usize], at: usize, size: usize) -> Vec<usize> {
32    let mut dims = dims.to_vec();
33    dims.insert(at, size);
34    dims
35}
36
37/// Maps a dimension of one example to the dimension of the batched value
38/// whose batch dimension is `bdim`.
39pub fn batched_dim(dim: usize, bdim: usize) -> usize {
40    if dim < bdim { dim } else { dim + 1 }
41}
42
43/// Returns `x` with its batch dimension at `to`, broadcasting it if it is
44/// unbatched.
45///
46/// # Errors
47///
48/// Returns an error if `to` is out of range.
49pub fn move_bdim(cx: &mut dyn BatchCx, x: &Batched, to: usize) -> Result<Atom> {
50    let aval = x.atom.aval();
51    match x.bdim {
52        Some(d) if d == to => Ok(x.atom.clone()),
53        Some(d) => {
54            // Result dimension `i` takes operand dimension `permutation[i]`.
55            let mut permutation: Vec<usize> = (0..aval.shape.rank()).filter(|&i| i != d).collect();
56            permutation.insert(to, d);
57            bind1(
58                cx,
59                TRANSPOSE,
60                std::slice::from_ref(&x.atom),
61                Params::Transpose { permutation },
62            )
63        }
64        None => {
65            let shape = insert_dim(aval.shape.dims(), to, cx.axis_size());
66            let broadcast_dimensions = (0..aval.shape.rank()).map(|i| batched_dim(i, to)).collect();
67            bind1(
68                cx,
69                BROADCAST_IN_DIM,
70                std::slice::from_ref(&x.atom),
71                Params::BroadcastInDim {
72                    shape: shape.into(),
73                    broadcast_dimensions,
74                },
75            )
76        }
77    }
78}
79
80/// Returns `x` with its batch dimension first, broadcasting it if it is
81/// unbatched.
82///
83/// # Errors
84///
85/// See [`move_bdim`].
86pub fn bdim_at_front(cx: &mut dyn BatchCx, x: &Batched) -> Result<Atom> {
87    move_bdim(cx, x, 0)
88}
89
90/// Broadcasts a batched value whose examples are scalars (shape `[n]`) to
91/// the batched shape `[n, example_shape...]`.
92pub(crate) fn broadcast_example_scalar(
93    cx: &mut dyn BatchCx,
94    x: &Atom,
95    example_shape: &Shape,
96) -> Result<Atom> {
97    if example_shape.rank() == 0 {
98        return Ok(x.clone());
99    }
100    let shape = insert_dim(example_shape.dims(), 0, cx.axis_size());
101    bind1(
102        cx,
103        BROADCAST_IN_DIM,
104        std::slice::from_ref(x),
105        Params::BroadcastInDim {
106            shape: shape.into(),
107            broadcast_dimensions: vec![0],
108        },
109    )
110}
111
112/// A scalar literal.
113pub(crate) fn literal(dtype: DType, value: Value) -> Atom {
114    Atom::Lit(Literal::new(HostArray::full(Shape::scalar(), dtype, value)))
115}
116
117/// The batching rule of elementwise primitives, whose operands have the same
118/// shape: operands batched at the same dimension are used as they are;
119/// otherwise every operand is moved (or broadcast) to have its batch
120/// dimension first.
121///
122/// # Errors
123///
124/// Returns an error from the primitive.
125pub fn elementwise(
126    cx: &mut dyn BatchCx,
127    prim: Prim,
128    inputs: &[Batched],
129    params: &Params,
130) -> Result<Vec<Batched>> {
131    let first = inputs.iter().find_map(|x| x.bdim);
132    let Some(first) = first else {
133        let atoms: Vec<Atom> = inputs.iter().map(|x| x.atom.clone()).collect();
134        let outs = cx.bind(prim, &atoms, params.clone())?;
135        return Ok(outs.into_iter().map(Batched::unmapped).collect());
136    };
137    let bdim = if inputs.iter().all(|x| x.bdim == Some(first)) {
138        first
139    } else {
140        0
141    };
142    let atoms = inputs
143        .iter()
144        .map(|x| move_bdim(cx, x, bdim))
145        .collect::<Result<Vec<_>>>()?;
146    let outs = cx.bind(prim, &atoms, params.clone())?;
147    Ok(outs.into_iter().map(|a| Batched::mapped(a, bdim)).collect())
148}
149
150/// Returns the batch dimension of the operand of a primitive with one
151/// operand, which is batched when its rule is called.
152///
153/// # Errors
154///
155/// Returns an error if the operand is not batched.
156pub(crate) fn batched_operand(prim: &'static str, x: &Batched) -> Result<usize> {
157    x.bdim.ok_or_else(|| {
158        Error::Malformed(format!(
159            "the batching rule of {prim} was called without batched operands"
160        ))
161    })
162}