Skip to main content

ruxla_core/
jit.rs

1//! `jit`: compiling programs with XLA.
2
3use std::any::Any;
4use std::collections::HashMap;
5use std::fmt;
6use std::sync::{Arc, Mutex, PoisonError};
7
8use ruxla_ir::{AVal, Function, HostArray, Params};
9use ruxla_pjrt::{Buffer, ExecuteOptions};
10
11use crate::backend::{Backend, Native, Trace};
12use crate::runtime::{self, Error, Platform};
13use crate::trace::{self, TraceRef, trace_function};
14use crate::transform::trace_with_output;
15use crate::tree::{Tree, TreeDef, leaves};
16
17/// Returns `f` compiled with XLA, like `jax.jit`.
18///
19/// `f` takes and returns pytrees of [`Trace`] values. The result is called
20///
21/// - with `Native` values ([`Jit::call`]): `f` is traced for the input types
22///   (once per combination of types and structure), compiled with XLA
23///   (cached), and run; inputs and outputs are copied to and from the
24///   device;
25/// - with values on the device ([`Jit::call_on_device`]), which stay there;
26/// - with `Trace` values inside another trace ([`Jit::call_traced`]): the
27///   traced body becomes a `jit` equation of the outer IR.
28///
29/// # Examples
30///
31/// ```no_run
32/// use ruxla_core::{Array, F32, Trace, jit, jnp};
33///
34/// let f = jit(|(x, y): (Array<Trace, f32>, F32<Trace>)| jnp::sin(&(x * y)));
35/// let out = f.call(&(Array::from_vec(vec![1.0f32, 2.0], [2]), F32::new(3.0)));
36/// assert_eq!(out.shape().to_vec(), [2]);
37/// ```
38pub fn jit<F>(f: F) -> Jit<F> {
39    Jit {
40        f,
41        name: String::from("jit"),
42        cache: Mutex::new(HashMap::new()),
43        skeletons: Mutex::new(HashMap::new()),
44    }
45}
46
47/// A function compiled with XLA; see [`jit`].
48pub struct Jit<F> {
49    f: F,
50    name: String,
51    cache: Mutex<HashMap<(TreeDef, Vec<AVal>), Specialization>>,
52    /// The structures of the results on the device, by the input's
53    /// structure and types (`O::On<Native>` with zeros).
54    skeletons: Mutex<HashMap<(TreeDef, Vec<AVal>), Specialization>>,
55}
56
57/// A [`Compiled`] of some output type, keyed by the input's structure and
58/// types.
59type Specialization = Arc<dyn Any + Send + Sync>;
60
61impl<F> fmt::Debug for Jit<F> {
62    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
63        f.debug_struct("Jit")
64            .field("name", &self.name)
65            .finish_non_exhaustive()
66    }
67}
68
69/// A traced and compiled specialization of a [`Jit`].
70struct Compiled<O> {
71    function: Function,
72    /// The output of tracing, whose structure (and static fields) the
73    /// results take.
74    out: O,
75    platform: Platform,
76}
77
78impl<F> Jit<F> {
79    /// Sets the name shown in the IR (the default is `jit`).
80    pub fn with_name(mut self, name: impl Into<String>) -> Self {
81        self.name = name.into();
82        self
83    }
84
85    fn compiled<I, O>(&self, input: &I) -> Arc<Compiled<O>>
86    where
87        I: Tree<Native>,
88        O: Tree<Trace> + Send + Sync + 'static,
89        F: Fn(I::On<Trace>) -> O,
90    {
91        let avals: Vec<AVal> = leaves(input).iter().map(Native::leaf_aval).collect();
92        let key = (input.def(), avals);
93        let cached = self
94            .cache
95            .lock()
96            .unwrap_or_else(PoisonError::into_inner)
97            .get(&key)
98            .cloned();
99        if let Some(c) = cached.and_then(|c| c.downcast::<Compiled<O>>().ok()) {
100            return c;
101        }
102        let (traced, out) = trace_with_output(&self.f, input);
103        let compiled = Arc::new(Compiled {
104            function: traced.function,
105            out,
106            platform: runtime::platform(),
107        });
108        self.cache
109            .lock()
110            .unwrap_or_else(PoisonError::into_inner)
111            .insert(key, compiled.clone());
112        compiled
113    }
114
115    /// Runs the function on `Native` values with XLA.
116    ///
117    /// # Panics
118    ///
119    /// Panics if the runtime fails (see [`Jit::try_call`]), or if `f` uses
120    /// traced values of another trace.
121    #[track_caller]
122    pub fn call<I, O>(&self, input: &I) -> O::On<Native>
123    where
124        I: Tree<Native>,
125        O: Tree<Trace> + Send + Sync + 'static,
126        F: Fn(I::On<Trace>) -> O,
127    {
128        self.try_call(input).unwrap_or_else(|e| panic!("{e}"))
129    }
130
131    /// Runs the function on `Native` values with XLA.
132    ///
133    /// # Errors
134    ///
135    /// Returns an error if no PJRT plugin is configured (see
136    /// [`runtime`](crate::runtime)), or if compiling or running fails.
137    pub fn try_call<I, O>(&self, input: &I) -> Result<O::On<Native>, Error>
138    where
139        I: Tree<Native>,
140        O: Tree<Trace> + Send + Sync + 'static,
141        F: Fn(I::On<Trace>) -> O,
142    {
143        let c = self.compiled::<I, O>(input);
144        let client = runtime::client(c.platform)?;
145        let buffers = leaves(input)
146            .iter()
147            .map(|a| client.buffer_from_host_array(a))
148            .collect::<Result<Vec<_>, _>>()?;
149        let outs = execute(&c, &buffers.iter().collect::<Vec<_>>())?;
150        let outs = outs
151            .iter()
152            .map(Buffer::to_host_array)
153            .collect::<Result<Vec<HostArray>, _>>()?;
154        Ok(c.out.rebuild::<Native>(&mut outs.into_iter()))
155    }
156
157    /// Runs the function with XLA on values on the device, and returns the
158    /// results on the device.
159    ///
160    /// # Panics
161    ///
162    /// Panics if the runtime fails, or if the values are on another
163    /// platform.
164    #[track_caller]
165    pub fn call_on_device<I, O>(&self, input: &OnDevice<I>) -> OnDevice<O::On<Native>>
166    where
167        I: Tree<Native>,
168        O: Tree<Trace> + Send + Sync + 'static,
169        O::On<Native>: Send + Sync + 'static,
170        F: Fn(I::On<Trace>) -> O,
171    {
172        let c = self.compiled::<I, O>(&input.skeleton);
173        assert_eq!(
174            c.platform, input.platform,
175            "the values are on another platform"
176        );
177        let args: Vec<&Buffer> = input.buffers.iter().map(Arc::as_ref).collect();
178        let exe = runtime::compile(c.platform, &c.function).unwrap_or_else(|e| panic!("{e}"));
179        // The device runs executions in order, so the results are returned
180        // without waiting; copying them to the host waits for them.
181        let (outs, _done) = exe
182            .execute_with(&args, &ExecuteOptions::default())
183            .unwrap_or_else(|e| panic!("{e}"));
184        self.on_device(&c, &input.skeleton, outs)
185    }
186
187    /// [`Jit::call_on_device`] taking the input, whose buffers the program
188    /// may reuse for the results (donation, as with JAX's
189    /// `donate_argnums`), which saves memory and copies in loops such as
190    /// `state = step.call_on_device_donating(state)`. Leaves whose buffers
191    /// are shared with another `OnDevice` (a clone) are not donated.
192    ///
193    /// # Panics
194    ///
195    /// Panics if the runtime fails, or if the values are on another
196    /// platform.
197    #[track_caller]
198    pub fn call_on_device_donating<I, O>(&self, input: OnDevice<I>) -> OnDevice<O::On<Native>>
199    where
200        I: Tree<Native>,
201        O: Tree<Trace> + Send + Sync + 'static,
202        O::On<Native>: Send + Sync + 'static,
203        F: Fn(I::On<Trace>) -> O,
204    {
205        let c = self.compiled::<I, O>(&input.skeleton);
206        assert_eq!(
207            c.platform, input.platform,
208            "the values are on another platform"
209        );
210        let donated = vec![true; input.buffers.len()];
211        let exe = runtime::compile_donating(c.platform, &c.function, &donated)
212            .unwrap_or_else(|e| panic!("{e}"));
213        let options = ExecuteOptions {
214            non_donatable: input
215                .buffers
216                .iter()
217                .enumerate()
218                .filter(|(_, b)| Arc::strong_count(b) > 1)
219                .map(|(i, _)| i as i64)
220                .collect(),
221        };
222        let args: Vec<&Buffer> = input.buffers.iter().map(Arc::as_ref).collect();
223        let (outs, _done) = exe
224            .execute_with(&args, &options)
225            .unwrap_or_else(|e| panic!("{e}"));
226        self.on_device(&c, &input.skeleton, outs)
227    }
228
229    /// Wraps the results of an execution on the device.
230    fn on_device<I, O>(
231        &self,
232        c: &Compiled<O>,
233        input: &I,
234        outs: Vec<Buffer>,
235    ) -> OnDevice<O::On<Native>>
236    where
237        I: Tree<Native>,
238        O: Tree<Trace> + Send + Sync + 'static,
239        O::On<Native>: Send + Sync + 'static,
240    {
241        let avals: Vec<AVal> = leaves(input).iter().map(Native::leaf_aval).collect();
242        let key = (input.def(), avals);
243        let cached = self
244            .skeletons
245            .lock()
246            .unwrap_or_else(PoisonError::into_inner)
247            .get(&key)
248            .cloned()
249            .and_then(|s| s.downcast::<O::On<Native>>().ok());
250        let skeleton = match cached {
251            Some(s) => (*s).clone(),
252            None => {
253                // Zeros of the output types, which give `to_native` the
254                // structure and static fields.
255                let zeros: Vec<HostArray> = c
256                    .function
257                    .out_avals()
258                    .iter()
259                    .map(|a| HostArray::zeros(a.shape.clone(), a.dtype))
260                    .collect();
261                let s = c.out.rebuild::<Native>(&mut zeros.into_iter());
262                self.skeletons
263                    .lock()
264                    .unwrap_or_else(PoisonError::into_inner)
265                    .insert(key, Arc::new(s.clone()));
266                s
267            }
268        };
269        OnDevice {
270            skeleton,
271            buffers: outs.into_iter().map(Arc::new).collect(),
272            platform: c.platform,
273        }
274    }
275
276    /// Calls the function on `Trace` values inside another trace, which
277    /// adds a `jit` equation with the traced body to the outer IR.
278    pub fn call_traced<I, O>(&self, input: I) -> O
279    where
280        I: Tree<Trace>,
281        O: Tree<Trace>,
282        F: Fn(I) -> O,
283    {
284        let args = leaves(&input);
285        let in_avals: Vec<AVal> = args.iter().map(|&r| trace::aval(r)).collect();
286        let mut out: Option<O> = None;
287        let traced = trace_function(&in_avals, |refs| {
288            let o = (self.f)(input.unflatten_like(&mut refs.iter().copied()));
289            let l = leaves(&o);
290            out = Some(o);
291            l
292        });
293        let mut inputs: Vec<TraceRef> = traced.captured;
294        inputs.extend(args);
295        let outs = trace::bind(
296            ruxla_prims::JIT,
297            &inputs,
298            Params::Jit {
299                name: self.name.clone(),
300                body: Arc::new(traced.function),
301            },
302        );
303        out.expect("the function was called")
304            .unflatten_like(&mut outs.into_iter())
305    }
306}
307
308fn execute<O>(c: &Compiled<O>, args: &[&Buffer]) -> Result<Vec<Buffer>, Error> {
309    let exe = runtime::compile(c.platform, &c.function)?;
310    Ok(exe.execute(args)?)
311}
312
313/// A pytree whose arrays are on the device of the runtime's platform, made
314/// by [`device_put`] or returned by [`Jit::call_on_device`].
315///
316/// There are no operations on it other than passing it to jitted functions
317/// and copying it back with [`OnDevice::to_native`].
318pub struct OnDevice<T> {
319    /// A value of the same structure and static fields (its arrays are not
320    /// the device values).
321    skeleton: T,
322    buffers: Vec<Arc<Buffer>>,
323    platform: Platform,
324}
325
326impl<T: Clone> Clone for OnDevice<T> {
327    fn clone(&self) -> Self {
328        Self {
329            skeleton: self.skeleton.clone(),
330            buffers: self.buffers.clone(),
331            platform: self.platform,
332        }
333    }
334}
335
336impl<T> fmt::Debug for OnDevice<T> {
337    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
338        f.debug_struct("OnDevice")
339            .field("platform", &self.platform)
340            .field("leaves", &self.buffers.len())
341            .finish_non_exhaustive()
342    }
343}
344
345impl<T: Tree<Native>> OnDevice<T> {
346    /// Copies the values to the host.
347    ///
348    /// # Panics
349    ///
350    /// Panics if the transfer fails.
351    pub fn to_native(&self) -> T {
352        let host: Vec<HostArray> = self
353            .buffers
354            .iter()
355            .map(|b| b.to_host_array().unwrap_or_else(|e| panic!("{e}")))
356            .collect();
357        self.skeleton.unflatten_like(&mut host.into_iter())
358    }
359}
360
361/// Copies a pytree of `Native` values to the device of the runtime's
362/// platform.
363///
364/// # Panics
365///
366/// Panics if no PJRT plugin is configured or the transfer fails.
367pub fn device_put<T: Tree<Native>>(x: &T) -> OnDevice<T> {
368    let platform = runtime::platform();
369    let client = runtime::client(platform).unwrap_or_else(|e| panic!("{e}"));
370    let buffers = leaves(x)
371        .iter()
372        .map(|a| {
373            client
374                .buffer_from_host_array(a)
375                .map(Arc::new)
376                .unwrap_or_else(|e| panic!("{e}"))
377        })
378        .collect();
379    OnDevice {
380        skeleton: x.clone(),
381        buffers,
382        platform,
383    }
384}