ruxla_ir/batching.rs
1//! The interface for batching primitives (`vmap`).
2//!
3//! `vmap` turns a function of single examples into a function of batches by
4//! applying each primitive's batching rule ([`Primitive::batch`]). A rule
5//! receives its operands with their batch dimensions ([`Batched`]) and emits
6//! batched operations through [`BatchCx`]. The driver, which walks the
7//! equations of a function, lives in `ruxla-transforms`.
8//!
9//! [`Primitive::batch`]: crate::Primitive::batch
10
11use std::collections::HashMap;
12
13use crate::error::Result;
14use crate::function::{Atom, Function, Params};
15use crate::host::HostArray;
16use crate::primitive::Prim;
17use crate::shape::AVal;
18
19/// A value of the batched function and the position of its batch dimension,
20/// or `None` if it is the same for every example of the batch.
21#[derive(Clone, Debug, PartialEq)]
22pub struct Batched {
23 /// The value.
24 pub atom: Atom,
25 /// The batch dimension, if the value is batched.
26 pub bdim: Option<usize>,
27}
28
29impl Batched {
30 /// A batched value.
31 pub fn mapped(atom: Atom, bdim: usize) -> Self {
32 Self {
33 atom,
34 bdim: Some(bdim),
35 }
36 }
37
38 /// A value that is the same for every example.
39 pub fn unmapped(atom: Atom) -> Self {
40 Self { atom, bdim: None }
41 }
42
43 /// Returns the abstract value of one example: the value's abstract value
44 /// without the batch dimension.
45 pub fn example_aval(&self) -> AVal {
46 let aval = self.atom.aval();
47 match self.bdim {
48 None => aval,
49 Some(d) => {
50 let mut dims = aval.shape.dims().to_vec();
51 dims.remove(d);
52 AVal::new(dims, aval.dtype)
53 }
54 }
55 }
56}
57
58/// The body given to [`BatchCx::build_function`]: emits operations through
59/// the context it receives, from the inputs of the new function, and returns
60/// its outputs.
61pub type BuildBody<'a> = dyn FnMut(&mut dyn BatchCx, &[Atom]) -> Result<Vec<Atom>> + 'a;
62
63/// A context that emits the operations of a batched function.
64pub trait BatchCx {
65 /// Returns the size of the batch.
66 fn axis_size(&self) -> usize;
67
68 /// Applies a primitive to atoms of the batched function and returns its
69 /// outputs.
70 ///
71 /// # Errors
72 ///
73 /// Returns an error if the primitive rejects the inputs.
74 fn bind(&mut self, prim: Prim, inputs: &[Atom], params: Params) -> Result<Vec<Atom>>;
75
76 /// Returns an atom holding a constant array.
77 fn constant(&mut self, value: HostArray) -> Atom;
78
79 /// Batches a nested function (the body of `jit`, `scan`, ...) whose
80 /// inputs have the batch dimensions `in_axes`.
81 ///
82 /// In the result, batched outputs have their batch dimension first.
83 /// `force[i]` requires output `i` to be batched (`Some(true)`, by
84 /// broadcasting it if needed) or unbatched (`Some(false)`); `None` leaves
85 /// it as it comes. Returns the function and which outputs are batched.
86 ///
87 /// # Errors
88 ///
89 /// Returns an error if a primitive of `f` cannot be batched, or if an
90 /// output that must be unbatched is batched.
91 fn batch_function(
92 &mut self,
93 f: &Function,
94 in_axes: &[Option<usize>],
95 force: &[Option<bool>],
96 ) -> Result<(Function, Vec<bool>)>;
97
98 /// Builds a new function with inputs `in_avals` from the operations that
99 /// `body` emits through the context it receives (with the same batch
100 /// size). Atoms of this context must not be used inside `body`.
101 ///
102 /// # Errors
103 ///
104 /// Returns an error from `body`.
105 fn build_function(&mut self, in_avals: &[AVal], body: &mut BuildBody<'_>) -> Result<Function>;
106}
107
108/// Emits the equations of `f` applied to `args` into `cx`, and returns the
109/// outputs.
110///
111/// # Errors
112///
113/// Returns an error if a primitive rejects its inputs, or if `args` do not
114/// match the inputs of `f`.
115pub fn inline(cx: &mut dyn BatchCx, f: &Function, args: &[Atom]) -> Result<Vec<Atom>> {
116 if args.len() != f.invars.len() {
117 return Err(crate::Error::Malformed(format!(
118 "a function of {} inputs was applied to {} arguments",
119 f.invars.len(),
120 args.len()
121 )));
122 }
123 let mut env: HashMap<u64, Atom> = HashMap::new();
124 for (v, value) in &f.constvars {
125 env.insert(v.id(), cx.constant(value.clone()));
126 }
127 for (v, a) in f.invars.iter().zip(args) {
128 env.insert(v.id(), a.clone());
129 }
130 let read = |env: &HashMap<u64, Atom>, a: &Atom| match a {
131 Atom::Var(v) => env
132 .get(&v.id())
133 .cloned()
134 .ok_or_else(|| crate::Error::Malformed(format!("undefined variable {v:?}"))),
135 Atom::Lit(_) => Ok(a.clone()),
136 };
137 for eqn in &f.eqns {
138 let inputs = eqn
139 .inputs
140 .iter()
141 .map(|a| read(&env, a))
142 .collect::<Result<Vec<_>>>()?;
143 let outputs = cx.bind(eqn.prim, &inputs, eqn.params.clone())?;
144 for (v, a) in eqn.outputs.iter().zip(outputs) {
145 env.insert(v.id(), a);
146 }
147 }
148 f.outvars.iter().map(|a| read(&env, a)).collect()
149}