Skip to main content

ruxla_core/
vmap.rs

1//! `vmap`: batching programs.
2
3use std::fmt;
4
5use std::sync::Arc;
6
7use ruxla_ir::{AVal, HostArray, Params};
8use ruxla_pjrt::Buffer;
9
10use crate::backend::{Native, Trace};
11use crate::runtime::{self, Error};
12use crate::trace::{self, TraceRef, trace_function};
13use crate::transform::trace_with_output;
14use crate::tree::{Tree, leaves};
15
16/// Returns `f` batched over examples, like `jax.vmap` with every input and
17/// output batched at dimension 0.
18///
19/// `f` takes and returns pytrees of [`Trace`] values for one example. It is
20/// traced once, and the IR is batched by ruxla's `vmap` (the same
21/// transformation that JAX's `vmap` of an exported program uses), so the
22/// batched program has no loop. [`Vmap::call`] runs it with the interpreter
23/// and [`Vmap::call_xla`] with XLA. To run a generic program natively for
24/// many examples, call it in a loop (or use `ruxla_env::VecEnv`).
25///
26/// # Examples
27///
28/// ```
29/// use ruxla_core::{F32, Trace, vmap};
30///
31/// let f = vmap(|(x, y): (F32<Trace>, F32<Trace>)| x * y + 1.0);
32/// let out = f.call(&[(F32::new(2.0), F32::new(3.0)), (F32::new(4.0), F32::new(0.5))]);
33/// assert_eq!(out.iter().map(|v| v.value()).collect::<Vec<_>>(), [7.0, 3.0]);
34/// ```
35pub fn vmap<F>(f: F) -> Vmap<F> {
36    Vmap { f }
37}
38
39/// A batched function; see [`vmap`].
40pub struct Vmap<F> {
41    f: F,
42}
43
44impl<F> fmt::Debug for Vmap<F> {
45    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
46        f.debug_struct("Vmap").finish_non_exhaustive()
47    }
48}
49
50/// A batched function, its stacked arguments, and the structure of one
51/// output.
52struct Batched<O> {
53    function: ruxla_ir::Function,
54    args: Vec<HostArray>,
55    out: O,
56    size: usize,
57}
58
59/// Stacks arrays of the same type along a new leading dimension.
60fn stack(xs: &[HostArray]) -> HostArray {
61    let first = &xs[0];
62    let mut bytes = Vec::with_capacity(first.to_bytes().len() * xs.len());
63    for x in xs {
64        assert_eq!(
65            x.aval(),
66            first.aval(),
67            "vmap: the examples must have the same types"
68        );
69        bytes.extend(x.to_bytes());
70    }
71    let mut shape = vec![xs.len()];
72    shape.extend_from_slice(first.shape());
73    HostArray::from_bytes(&bytes, shape, first.dtype()).expect("consistent sizes")
74}
75
76/// Element `i` along the leading dimension.
77fn unstack(x: &HostArray, i: usize) -> HostArray {
78    let shape = x.shape()[1..].to_vec();
79    let n: usize = shape.iter().product::<usize>() * x.dtype().size_in_bytes();
80    HostArray::from_bytes(&x.to_bytes()[i * n..(i + 1) * n], shape, x.dtype())
81        .expect("consistent sizes")
82}
83
84impl<F> Vmap<F> {
85    fn batch<I, O>(&self, examples: &[I]) -> Batched<O>
86    where
87        I: Tree<Native>,
88        O: Tree<Trace>,
89        F: Fn(I::On<Trace>) -> O,
90    {
91        assert!(!examples.is_empty(), "vmap needs at least one example");
92        let (traced, out) = trace_with_output(&self.f, &examples[0]);
93        let per_example: Vec<Vec<HostArray>> = examples
94            .iter()
95            .map(|e| {
96                assert_eq!(
97                    e.def(),
98                    traced.in_def,
99                    "vmap: the examples must have the same structure"
100                );
101                leaves(e)
102            })
103            .collect();
104        let args = (0..per_example[0].len())
105            .map(|j| stack(&per_example.iter().map(|l| l[j].clone()).collect::<Vec<_>>()))
106            .collect();
107        let n = examples.len();
108        let in_axes = vec![Some(0); traced.function.invars.len()];
109        let out_axes = vec![Some(0); traced.function.outvars.len()];
110        let function =
111            ruxla_transforms::vmap_with_out_axes(&traced.function, &in_axes, &out_axes, n)
112                .unwrap_or_else(|e| panic!("vmap: {e}"));
113        Batched {
114            function,
115            args,
116            out,
117            size: n,
118        }
119    }
120
121    fn unbatch<O: Tree<Trace>>(b: &Batched<O>, outs: &[HostArray]) -> Vec<O::On<Native>> {
122        (0..b.size)
123            .map(|i| {
124                let leaves: Vec<HostArray> = outs.iter().map(|x| unstack(x, i)).collect();
125                b.out.rebuild::<Native>(&mut leaves.into_iter())
126            })
127            .collect()
128    }
129
130    /// Runs the batched program on `examples` with the interpreter and
131    /// returns one output per example.
132    ///
133    /// # Panics
134    ///
135    /// Panics if there are no examples, if they differ in structure or
136    /// types, or if a primitive cannot be batched.
137    pub fn call<I, O>(&self, examples: &[I]) -> Vec<O::On<Native>>
138    where
139        I: Tree<Native>,
140        O: Tree<Trace>,
141        F: Fn(I::On<Trace>) -> O,
142    {
143        let b = self.batch(examples);
144        let outs = ruxla_interp::eval(&b.function, &b.args).unwrap_or_else(|e| panic!("{e}"));
145        Self::unbatch(&b, &outs)
146    }
147
148    /// Runs the batched program on `examples` with XLA and returns one
149    /// output per example.
150    ///
151    /// # Errors
152    ///
153    /// Returns an error if no PJRT plugin is configured, or if compiling or
154    /// running fails.
155    ///
156    /// # Panics
157    ///
158    /// See [`Vmap::call`].
159    pub fn call_xla<I, O>(&self, examples: &[I]) -> Result<Vec<O::On<Native>>, Error>
160    where
161        I: Tree<Native>,
162        O: Tree<Trace>,
163        F: Fn(I::On<Trace>) -> O,
164    {
165        let b = self.batch(examples);
166        let platform = runtime::platform();
167        let client = runtime::client(platform)?;
168        let exe = runtime::compile(platform, &b.function)?;
169        let buffers = b
170            .args
171            .iter()
172            .map(|a| client.buffer_from_host_array(a))
173            .collect::<Result<Vec<_>, _>>()?;
174        let outs = exe.execute(&buffers.iter().collect::<Vec<_>>())?;
175        let outs = outs
176            .iter()
177            .map(Buffer::to_host_array)
178            .collect::<Result<Vec<HostArray>, _>>()?;
179        Ok(Self::unbatch(&b, &outs))
180    }
181
182    /// Calls the batched function inside another trace on `examples`,
183    /// pytrees of `Trace` values whose arrays are stacked along a new
184    /// leading dimension (the number of examples). The batched body becomes
185    /// a `jit` equation of the outer IR. Values that `f` captures from the
186    /// outer trace are shared by all examples (not batched).
187    ///
188    /// The stacked values have the types of one example, so a stacked
189    /// [`Scalar`](crate::Scalar) holds an array of rank 1: pass such values
190    /// on (to another `vmap`, a loop's carry, or an output) without
191    /// computing with them, and return arrays of rank 0 from `f` for values
192    /// to compute with afterwards.
193    ///
194    /// # Examples
195    ///
196    /// ```
197    /// use ruxla_core::{Array, F32, Trace, interpret, vmap};
198    ///
199    /// let f = |(xs, y): (Array<Trace, f32>, F32<Trace>)| {
200    ///     vmap(|x: Array<Trace, f32>| x * y).call_traced(xs)
201    /// };
202    /// let out = interpret(f, &(Array::from_vec(vec![1.0f32, 2.0, 3.0], [3]), F32::new(2.0)));
203    /// assert_eq!(out.to_vec(), [2.0, 4.0, 6.0]);
204    /// ```
205    ///
206    /// # Panics
207    ///
208    /// Panics if the leaves of `examples` do not have the same leading
209    /// dimension, or if a primitive cannot be batched.
210    pub fn call_traced<I, O>(&self, examples: I) -> O
211    where
212        I: Tree<Trace>,
213        O: Tree<Trace>,
214        F: Fn(I) -> O,
215    {
216        let args: Vec<TraceRef> = leaves(&examples);
217        let avals: Vec<AVal> = args.iter().map(|&r| trace::aval(r)).collect();
218        let n = avals
219            .first()
220            .and_then(|a| a.shape.first().copied())
221            .expect("vmap needs an input array with a leading dimension");
222        let in_avals: Vec<AVal> = avals
223            .iter()
224            .map(|a| {
225                assert_eq!(
226                    a.shape.first(),
227                    Some(&n),
228                    "vmap: the inputs must have the same leading dimension"
229                );
230                AVal::new(a.shape[1..].to_vec(), a.dtype)
231            })
232            .collect();
233        let mut out: Option<O> = None;
234        let traced = trace_function(&in_avals, |refs| {
235            let o = (self.f)(examples.unflatten_like(&mut refs.iter().copied()));
236            let l = leaves(&o);
237            out = Some(o);
238            l
239        });
240        let ncap = traced.captured.len();
241        let mut in_axes = vec![None; ncap];
242        in_axes.extend(vec![Some(0); args.len()]);
243        let out_axes = vec![Some(0); traced.function.outvars.len()];
244        let body = ruxla_transforms::vmap_with_out_axes(&traced.function, &in_axes, &out_axes, n)
245            .unwrap_or_else(|e| panic!("vmap: {e}"));
246        let mut inputs = traced.captured;
247        inputs.extend(args);
248        let outs = trace::bind(
249            ruxla_prims::JIT,
250            &inputs,
251            Params::Jit {
252                name: String::from("vmap"),
253                body: Arc::new(body),
254            },
255        );
256        out.expect("the function was called")
257            .unflatten_like(&mut outs.into_iter())
258    }
259
260    /// Returns the batched IR for `n` examples shaped like `example`.
261    ///
262    /// # Panics
263    ///
264    /// Panics if a primitive cannot be batched.
265    pub fn make_ir<I, O>(&self, example: &I, n: usize) -> ruxla_ir::Function
266    where
267        I: Tree<Native>,
268        O: Tree<Trace>,
269        F: Fn(I::On<Trace>) -> O,
270    {
271        let (traced, _) = trace_with_output(&self.f, example);
272        let in_avals: Vec<AVal> = traced.function.in_avals();
273        let in_axes = vec![Some(0); in_avals.len()];
274        let out_axes = vec![Some(0); traced.function.outvars.len()];
275        ruxla_transforms::vmap_with_out_axes(&traced.function, &in_axes, &out_axes, n)
276            .unwrap_or_else(|e| panic!("vmap: {e}"))
277    }
278}