Skip to main content

ruxla_transforms/
batching.rs

1//! `vmap`: batching a function by applying each primitive's batching rule.
2
3use std::collections::HashMap;
4
5use ruxla_ir::batching::{BatchCx, Batched, BuildBody};
6use ruxla_ir::{AVal, Atom, Eqn, Error, Function, HostArray, Literal, Params, Prim, Result, Var};
7use ruxla_prims::batching::{insert_dim, move_bdim};
8
9/// What the batched function must do with an output.
10#[derive(Clone, Copy, Debug, PartialEq, Eq)]
11enum OutSpec {
12    /// Batched at dimension 0 if batched, unbatched otherwise.
13    Free,
14    /// Unbatched; an error if it is batched.
15    Unbatched,
16    /// Batched at this dimension, broadcast if needed.
17    At(usize),
18}
19
20/// Emits the equations of a batched function.
21struct Builder {
22    axis_size: usize,
23    constvars: Vec<(Var, HostArray)>,
24    eqns: Vec<Eqn>,
25    /// The source location of the equation being batched.
26    loc: Option<ruxla_ir::SrcLoc>,
27}
28
29impl Builder {
30    fn new(axis_size: usize) -> Self {
31        Self {
32            axis_size,
33            constvars: Vec::new(),
34            eqns: Vec::new(),
35            loc: None,
36        }
37    }
38
39    fn finish(self, invars: Vec<Var>, outvars: Vec<Atom>) -> Function {
40        Function {
41            constvars: self.constvars,
42            invars,
43            eqns: self.eqns,
44            outvars,
45        }
46    }
47}
48
49impl BatchCx for Builder {
50    fn axis_size(&self) -> usize {
51        self.axis_size
52    }
53
54    fn bind(&mut self, prim: Prim, inputs: &[Atom], params: Params) -> Result<Vec<Atom>> {
55        let avals: Vec<AVal> = inputs.iter().map(Atom::aval).collect();
56        let outputs: Vec<Var> = prim
57            .abstract_eval(&avals, &params)?
58            .into_iter()
59            .map(Var::new)
60            .collect();
61        self.eqns.push(Eqn {
62            prim,
63            inputs: inputs.to_vec(),
64            params,
65            outputs: outputs.clone(),
66            loc: self.loc,
67        });
68        Ok(outputs.into_iter().map(Atom::Var).collect())
69    }
70
71    fn constant(&mut self, value: HostArray) -> Atom {
72        if value.shape().rank() == 0 {
73            return Atom::Lit(Literal::new(value));
74        }
75        let var = Var::new(AVal::new(value.shape().clone(), value.dtype()));
76        self.constvars.push((var.clone(), value));
77        Atom::Var(var)
78    }
79
80    fn batch_function(
81        &mut self,
82        f: &Function,
83        in_axes: &[Option<usize>],
84        force: &[Option<bool>],
85    ) -> Result<(Function, Vec<bool>)> {
86        let specs: Vec<OutSpec> = force
87            .iter()
88            .map(|f| match f {
89                None => OutSpec::Free,
90                Some(false) => OutSpec::Unbatched,
91                Some(true) => OutSpec::At(0),
92            })
93            .collect();
94        let (g, out_axes) = batch(f, in_axes, &specs, self.axis_size)?;
95        Ok((g, out_axes.iter().map(Option::is_some).collect()))
96    }
97
98    fn build_function(&mut self, in_avals: &[AVal], body: &mut BuildBody<'_>) -> Result<Function> {
99        let mut builder = Builder::new(self.axis_size);
100        builder.loc = self.loc;
101        let invars: Vec<Var> = in_avals.iter().cloned().map(Var::new).collect();
102        let args: Vec<Atom> = invars.iter().cloned().map(Atom::Var).collect();
103        let outs = body(&mut builder, &args)?;
104        Ok(builder.finish(invars, outs))
105    }
106}
107
108fn read(env: &HashMap<u64, Batched>, a: &Atom) -> Result<Batched> {
109    match a {
110        Atom::Var(v) => env
111            .get(&v.id())
112            .cloned()
113            .ok_or_else(|| Error::Malformed(format!("undefined variable {v:?}"))),
114        Atom::Lit(_) => Ok(Batched::unmapped(a.clone())),
115    }
116}
117
118/// Batches `f` and returns the batched function with the batch dimension
119/// of each output (`None` if unbatched).
120fn batch(
121    f: &Function,
122    in_axes: &[Option<usize>],
123    out_specs: &[OutSpec],
124    axis_size: usize,
125) -> Result<(Function, Vec<Option<usize>>)> {
126    if in_axes.len() != f.invars.len() {
127        return Err(Error::Malformed(format!(
128            "vmap: {} input axes for a function of {} inputs",
129            in_axes.len(),
130            f.invars.len()
131        )));
132    }
133    if out_specs.len() != f.outvars.len() {
134        return Err(Error::Malformed(format!(
135            "vmap: {} output axes for a function of {} outputs",
136            out_specs.len(),
137            f.outvars.len()
138        )));
139    }
140    let mut b = Builder::new(axis_size);
141    let mut env: HashMap<u64, Batched> = HashMap::new();
142    for (v, value) in &f.constvars {
143        let atom = b.constant(value.clone());
144        env.insert(v.id(), Batched::unmapped(atom));
145    }
146    let mut invars = Vec::new();
147    for (v, &axis) in f.invars.iter().zip(in_axes) {
148        let aval = v.aval();
149        let aval = match axis {
150            None => aval.clone(),
151            Some(d) if d <= aval.shape.rank() => AVal {
152                shape: insert_dim(aval.shape.dims(), d, axis_size).into(),
153                ..aval.clone()
154            },
155            Some(d) => {
156                return Err(Error::Malformed(format!(
157                    "vmap: axis {d} is out of range for an input {aval}"
158                )));
159            }
160        };
161        let var = Var::new(aval);
162        invars.push(var.clone());
163        env.insert(
164            v.id(),
165            Batched {
166                atom: Atom::Var(var),
167                bdim: axis,
168            },
169        );
170    }
171
172    for eqn in &f.eqns {
173        let inputs = eqn
174            .inputs
175            .iter()
176            .map(|a| read(&env, a))
177            .collect::<Result<Vec<_>>>()?;
178        b.loc = eqn.loc;
179        let outs = if inputs.iter().all(|x| x.bdim.is_none()) {
180            // Unbatched equations are kept as they are.
181            let atoms: Vec<Atom> = inputs.into_iter().map(|x| x.atom).collect();
182            b.bind(eqn.prim, &atoms, eqn.params.clone())?
183                .into_iter()
184                .map(Batched::unmapped)
185                .collect()
186        } else {
187            eqn.prim.batch(&mut b, &inputs, &eqn.params)?
188        };
189        if outs.len() != eqn.outputs.len() {
190            return Err(Error::Malformed(format!(
191                "the batching rule of {} returned {} outputs, expected {}",
192                eqn.prim.name(),
193                outs.len(),
194                eqn.outputs.len()
195            )));
196        }
197        for (v, out) in eqn.outputs.iter().zip(outs) {
198            let in_range = out.bdim.is_none_or(|d| d < out.atom.aval().shape.rank());
199            if !in_range || out.example_aval() != *v.aval() {
200                return Err(Error::Malformed(format!(
201                    "the batching rule of {} returned {} at {:?} for an output {}",
202                    eqn.prim.name(),
203                    out.atom.aval(),
204                    out.bdim,
205                    v.aval()
206                )));
207            }
208            env.insert(v.id(), out);
209        }
210    }
211
212    let mut outvars = Vec::new();
213    let mut out_axes = Vec::new();
214    for (a, &spec) in f.outvars.iter().zip(out_specs) {
215        let x = read(&env, a)?;
216        let (atom, axis) = match (x.bdim, spec) {
217            (None, OutSpec::Free | OutSpec::Unbatched) => (x.atom, None),
218            (Some(_), OutSpec::Unbatched) => {
219                return Err(Error::Malformed(format!(
220                    "vmap: an output ({}) that must be the same for every example depends on \
221                     the batched inputs",
222                    x.example_aval()
223                )));
224            }
225            (Some(_), OutSpec::Free) => (move_bdim(&mut b, &x, 0)?, Some(0)),
226            (_, OutSpec::At(d)) => {
227                let rank = x.example_aval().shape.rank();
228                if d > rank {
229                    return Err(Error::Malformed(format!(
230                        "vmap: output axis {d} is out of range for an output of rank {rank}"
231                    )));
232                }
233                (move_bdim(&mut b, &x, d)?, Some(d))
234            }
235        };
236        outvars.push(atom);
237        out_axes.push(axis);
238    }
239    Ok((b.finish(invars, outvars), out_axes))
240}
241
242/// Batches `f` over a batch of `axis_size` examples.
243///
244/// `in_axes[i]` is the dimension of input `i` that indexes the examples, or
245/// `None` if the input is the same for every example. Returns the batched
246/// function and, for each output, its batch dimension: `Some(0)` if it
247/// depends on the batched inputs and `None` otherwise.
248///
249/// The batched function computes the same values as applying `f` to each
250/// example and stacking the results, without a loop: each primitive is
251/// replaced by its batched form, following JAX's batching rules.
252///
253/// # Errors
254///
255/// Returns an error if `in_axes` does not match the inputs of `f`, or if a
256/// primitive cannot be batched ([`Error::Unsupported`]).
257///
258/// # Examples
259///
260/// ```
261/// use ruxla_ir::{AVal, Atom, DType, Eqn, Function, Params, Var};
262///
263/// // f(x) = sin(x) for x: f32[3]
264/// let x = Var::new(AVal::new([3], DType::F32));
265/// let y = Var::new(AVal::new([3], DType::F32));
266/// let f = Function {
267///     invars: vec![x.clone()],
268///     eqns: vec![Eqn {
269///         prim: ruxla_prims::SIN,
270///         inputs: vec![Atom::Var(x)],
271///         params: Params::None,
272///         outputs: vec![y.clone()],
273///         loc: None,
274///     }],
275///     outvars: vec![Atom::Var(y)],
276///     ..Function::default()
277/// };
278/// let (g, out_axes) = ruxla_transforms::vmap(&f, &[Some(1)], 5).unwrap();
279/// assert_eq!(g.in_avals()[0], AVal::new([3, 5], DType::F32));
280/// assert_eq!(g.out_avals()[0], AVal::new([5, 3], DType::F32));
281/// assert_eq!(out_axes, [Some(0)]);
282/// ```
283pub fn vmap(
284    f: &Function,
285    in_axes: &[Option<usize>],
286    axis_size: usize,
287) -> Result<(Function, Vec<Option<usize>>)> {
288    batch(f, in_axes, &vec![OutSpec::Free; f.outvars.len()], axis_size)
289}
290
291/// [`vmap`] with the batch dimension of each output: `Some(d)` puts it at
292/// dimension `d` (broadcasting outputs that do not depend on the batched
293/// inputs), and `None` requires the output to be the same for every example.
294///
295/// # Errors
296///
297/// Returns the errors of [`vmap`], and an error if an output with `None`
298/// depends on the batched inputs.
299pub fn vmap_with_out_axes(
300    f: &Function,
301    in_axes: &[Option<usize>],
302    out_axes: &[Option<usize>],
303    axis_size: usize,
304) -> Result<Function> {
305    let specs: Vec<OutSpec> = out_axes
306        .iter()
307        .map(|a| a.map_or(OutSpec::Unbatched, OutSpec::At))
308        .collect();
309    Ok(batch(f, in_axes, &specs, axis_size)?.0)
310}