Skip to main content

ruxla_core/
runtime.rs

1//! The XLA runtime: PJRT clients and the cache of compiled functions.
2//!
3//! Jitted functions run on one platform per process:
4//!
5//! - [`set_platform`] sets it explicitly;
6//! - otherwise, the environment variable `RUXLA_PLATFORM` (`cpu` or `cuda`)
7//!   is used;
8//! - otherwise, the CPU.
9//!
10//! The plugin of a platform is taken from [`set_plugin_path`], then from
11//! `RUXLA_PJRT_CPU_PLUGIN` or `RUXLA_PJRT_CUDA_PLUGIN`, then from the
12//! directory `RUXLA_PJRT_PLUGIN_DIR` ([`Platform::plugin_file`]:
13//! `libpjrt_cpu.so`, `libpjrt_cpu.dylib` on macOS, `xla_cuda_plugin.so`),
14//! where `scripts/fetch-pjrt-plugins.sh` can put them. Without any of these:
15//!
16//! - the cache `RUXLA_CACHE_DIR/pjrt` (or `~/.cache/ruxla/pjrt`);
17//! - for CUDA on Linux, the plugin of the JAX installed for Python
18//!   (`jax[cuda13]` or `jax[cuda12]`, found with `RUXLA_PYTHON` or `python3`);
19//! - for the CPU on x86-64 and AArch64 Linux and on Apple silicon macOS, a
20//!   prebuilt plugin downloaded into the cache on first use (with `curl` and
21//!   `tar`, checked against a pinned SHA-256); `RUXLA_PJRT_DOWNLOAD=0` turns
22//!   the download off.
23//!
24//! On other platforms (Windows, Intel macOS, ...), there is no plugin to
25//! download: XLA from Rust needs a plugin given with [`set_plugin_path`] or
26//! the variables above. Everything that does not run XLA from Rust (the
27//! `Native` backend, tracing, `VecEnv`, environments compiled ahead of time,
28//! and the export to JAX) works without a plugin.
29//!
30//! Compiled executables are cached in memory, keyed by the platform and the
31//! serialized IR, which includes the input types.
32
33use std::collections::HashMap;
34use std::path::PathBuf;
35use std::sync::{Arc, Mutex, OnceLock, PoisonError};
36
37use ruxla_ir::Function;
38use ruxla_ir::lowering::Target;
39use ruxla_pjrt::{Client, ClientOption, LoadedExecutable, Plugin};
40
41mod plugins;
42
43/// An error of the XLA runtime.
44#[derive(Debug, thiserror::Error)]
45#[non_exhaustive]
46pub enum Error {
47    /// No plugin is configured for the platform.
48    #[error(
49        "no PJRT plugin found for {0:?}; call ruxla::runtime::set_plugin_path, set {env} or \
50         RUXLA_PJRT_PLUGIN_DIR (a directory with {file}), or install jax[cuda13] for CUDA on \
51         Linux (the CPU plugin is downloaded on x86-64 and AArch64 Linux and Apple silicon \
52         macOS unless RUXLA_PJRT_DOWNLOAD=0){none}",
53        env = .0.plugin_env(),
54        file = .0.plugin_file(),
55        none = if plugins::CPU_ARCHIVE.is_none() {
56            "; there is no prebuilt CPU plugin for this platform"
57        } else {
58            ""
59        }
60    )]
61    NoPlugin(Platform),
62    /// The function could not be lowered to StableHLO.
63    #[error("failed to lower to StableHLO: {0}")]
64    Lowering(#[from] ruxla_ir::Error),
65    /// The plugin failed to load, compile, transfer, or execute.
66    #[error(transparent)]
67    Pjrt(#[from] ruxla_pjrt::Error),
68}
69
70/// A platform that runs jitted functions.
71#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
72#[non_exhaustive]
73pub enum Platform {
74    /// The PJRT CPU plugin.
75    Cpu,
76    /// The PJRT CUDA plugin.
77    Cuda,
78}
79
80impl Platform {
81    /// The file name of the platform's plugin, as looked for in
82    /// `RUXLA_PJRT_PLUGIN_DIR` and in the cache: `libpjrt_cpu.so`
83    /// (`libpjrt_cpu.dylib` on macOS) or `xla_cuda_plugin.so`.
84    pub fn plugin_file(self) -> &'static str {
85        match self {
86            Platform::Cpu => ruxla_pjrt::CPU_PLUGIN_FILE,
87            Platform::Cuda => ruxla_pjrt::CUDA_PLUGIN_FILE,
88        }
89    }
90
91    fn plugin_env(self) -> &'static str {
92        match self {
93            Platform::Cpu => "RUXLA_PJRT_CPU_PLUGIN",
94            Platform::Cuda => "RUXLA_PJRT_CUDA_PLUGIN",
95        }
96    }
97}
98
99#[derive(Default)]
100struct Config {
101    platform: Option<Platform>,
102    plugin_paths: HashMap<Platform, PathBuf>,
103}
104
105fn config() -> std::sync::MutexGuard<'static, Config> {
106    static CONFIG: OnceLock<Mutex<Config>> = OnceLock::new();
107    CONFIG
108        .get_or_init(Default::default)
109        .lock()
110        .unwrap_or_else(PoisonError::into_inner)
111}
112
113/// Sets the platform for the rest of the process.
114pub fn set_platform(platform: Platform) {
115    config().platform = Some(platform);
116}
117
118/// Sets the path of the PJRT plugin of a platform.
119pub fn set_plugin_path(platform: Platform, path: impl Into<PathBuf>) {
120    config().plugin_paths.insert(platform, path.into());
121}
122
123/// Returns the platform that runs jitted functions (see the module
124/// documentation).
125///
126/// # Panics
127///
128/// Panics if `RUXLA_PLATFORM` has an unknown value.
129pub fn platform() -> Platform {
130    let mut config = config();
131    if let Some(platform) = config.platform {
132        return platform;
133    }
134    let platform = match std::env::var("RUXLA_PLATFORM").as_deref() {
135        Ok("cpu") | Err(_) => Platform::Cpu,
136        Ok("cuda") => Platform::Cuda,
137        Ok(other) => panic!("unknown RUXLA_PLATFORM `{other}`; expected cpu or cuda"),
138    };
139    config.platform = Some(platform);
140    platform
141}
142
143fn plugin_path(platform: Platform) -> Option<PathBuf> {
144    if let Some(path) = config().plugin_paths.get(&platform) {
145        return Some(path.clone());
146    }
147    if let Some(path) = std::env::var_os(platform.plugin_env()) {
148        return Some(PathBuf::from(path));
149    }
150    if let Some(dir) = std::env::var_os("RUXLA_PJRT_PLUGIN_DIR") {
151        let path = PathBuf::from(dir).join(platform.plugin_file());
152        if path.exists() {
153            return Some(path);
154        }
155    }
156    plugins::find(platform)
157}
158
159/// Returns the client of a platform, creating it on first use.
160///
161/// # Errors
162///
163/// Returns an error if the platform's plugin is not configured or fails to
164/// load.
165pub fn client(platform: Platform) -> Result<Client, Error> {
166    static CLIENTS: OnceLock<Mutex<HashMap<Platform, Client>>> = OnceLock::new();
167    let mut clients = CLIENTS
168        .get_or_init(Default::default)
169        .lock()
170        .unwrap_or_else(PoisonError::into_inner);
171    if let Some(client) = clients.get(&platform) {
172        return Ok(client.clone());
173    }
174    let path = plugin_path(platform).ok_or(Error::NoPlugin(platform))?;
175    let plugin = Plugin::load(&path)?;
176    // The handlers of the custom calls that primitives without StableHLO
177    // operations (linear algebra) lower to.
178    let ffi_platform = match platform {
179        Platform::Cpu => "Host",
180        Platform::Cuda => "CUDA",
181    };
182    ruxla_pjrt::linalg::register_handlers(plugin, ffi_platform)?;
183    let client = match platform {
184        // Allocate GPU memory on demand instead of reserving most of it.
185        Platform::Cuda => {
186            plugin.client_with_options(&[ClientOption::bool("preallocate", false)])?
187        }
188        Platform::Cpu => plugin.client()?,
189    };
190    clients.insert(platform, client.clone());
191    Ok(client)
192}
193
194/// The number of executables kept before the cache is emptied.
195const CACHE_CAPACITY: usize = 1024;
196
197/// Compiles a function for a platform, or returns the cached executable.
198///
199/// # Errors
200///
201/// Returns an error if the function cannot be lowered or compiled.
202pub(crate) fn compile(platform: Platform, f: &Function) -> Result<Arc<LoadedExecutable>, Error> {
203    compile_donating(platform, f, &[])
204}
205
206/// [`compile`], with the inputs marked `donated` given to the program for
207/// reuse as outputs (see `ruxla_stablehlo::LowerOptions`).
208pub(crate) fn compile_donating(
209    platform: Platform,
210    f: &Function,
211    donated: &[bool],
212) -> Result<Arc<LoadedExecutable>, Error> {
213    type Cache = HashMap<(Platform, Vec<u8>, Vec<bool>), Arc<LoadedExecutable>>;
214    static CACHE: OnceLock<Mutex<Cache>> = OnceLock::new();
215    let cache = CACHE.get_or_init(Default::default);
216    let key = (platform, ruxla_ir::serialize::to_bytes(f), donated.to_vec());
217    if let Some(exe) = cache
218        .lock()
219        .unwrap_or_else(PoisonError::into_inner)
220        .get(&key)
221    {
222        return Ok(exe.clone());
223    }
224    let client = client(platform)?;
225    let options = ruxla_stablehlo::LowerOptions {
226        target: Target::Pjrt,
227        platform: match platform {
228            Platform::Cpu => ruxla_ir::lowering::Platform::Cpu,
229            Platform::Cuda => ruxla_ir::lowering::Platform::Gpu,
230        },
231        donated: donated.to_vec(),
232    };
233    let module = ruxla_stablehlo::lower_with(f, &options)?;
234    let exe = Arc::new(client.compile(&module)?);
235    let mut cache = cache.lock().unwrap_or_else(PoisonError::into_inner);
236    if cache.len() >= CACHE_CAPACITY {
237        cache.clear();
238    }
239    cache.insert(key, exe.clone());
240    Ok(exe)
241}