ruxla-core 0.1.0

Internal crate of ruxla (use the `ruxla` crate): the frontend of ruxla (backend-generic values, native and tracing backends)
Documentation
//! The XLA runtime: PJRT clients and the cache of compiled functions.
//!
//! Jitted functions run on one platform per process:
//!
//! - [`set_platform`] sets it explicitly;
//! - otherwise, the environment variable `RUXLA_PLATFORM` (`cpu` or `cuda`)
//!   is used;
//! - otherwise, the CPU.
//!
//! The plugin of a platform is taken from [`set_plugin_path`], then from
//! `RUXLA_PJRT_CPU_PLUGIN` or `RUXLA_PJRT_CUDA_PLUGIN`, then from the
//! directory `RUXLA_PJRT_PLUGIN_DIR` ([`Platform::plugin_file`]:
//! `libpjrt_cpu.so`, `libpjrt_cpu.dylib` on macOS, `xla_cuda_plugin.so`),
//! where `scripts/fetch-pjrt-plugins.sh` can put them. Without any of these:
//!
//! - the cache `RUXLA_CACHE_DIR/pjrt` (or `~/.cache/ruxla/pjrt`);
//! - for CUDA on Linux, the plugin of the JAX installed for Python
//!   (`jax[cuda13]` or `jax[cuda12]`, found with `RUXLA_PYTHON` or `python3`);
//! - for the CPU on x86-64 and AArch64 Linux and on Apple silicon macOS, a
//!   prebuilt plugin downloaded into the cache on first use (with `curl` and
//!   `tar`, checked against a pinned SHA-256); `RUXLA_PJRT_DOWNLOAD=0` turns
//!   the download off.
//!
//! On other platforms (Windows, Intel macOS, ...), there is no plugin to
//! download: XLA from Rust needs a plugin given with [`set_plugin_path`] or
//! the variables above. Everything that does not run XLA from Rust (the
//! `Native` backend, tracing, `VecEnv`, environments compiled ahead of time,
//! and the export to JAX) works without a plugin.
//!
//! Compiled executables are cached in memory, keyed by the platform and the
//! serialized IR, which includes the input types.

use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::{Arc, Mutex, OnceLock, PoisonError};

use ruxla_ir::Function;
use ruxla_ir::lowering::Target;
use ruxla_pjrt::{Client, ClientOption, LoadedExecutable, Plugin};

mod plugins;

/// An error of the XLA runtime.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
    /// No plugin is configured for the platform.
    #[error(
        "no PJRT plugin found for {0:?}; call ruxla::runtime::set_plugin_path, set {env} or \
         RUXLA_PJRT_PLUGIN_DIR (a directory with {file}), or install jax[cuda13] for CUDA on \
         Linux (the CPU plugin is downloaded on x86-64 and AArch64 Linux and Apple silicon \
         macOS unless RUXLA_PJRT_DOWNLOAD=0){none}",
        env = .0.plugin_env(),
        file = .0.plugin_file(),
        none = if plugins::CPU_ARCHIVE.is_none() {
            "; there is no prebuilt CPU plugin for this platform"
        } else {
            ""
        }
    )]
    NoPlugin(Platform),
    /// The function could not be lowered to StableHLO.
    #[error("failed to lower to StableHLO: {0}")]
    Lowering(#[from] ruxla_ir::Error),
    /// The plugin failed to load, compile, transfer, or execute.
    #[error(transparent)]
    Pjrt(#[from] ruxla_pjrt::Error),
}

/// A platform that runs jitted functions.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Platform {
    /// The PJRT CPU plugin.
    Cpu,
    /// The PJRT CUDA plugin.
    Cuda,
}

impl Platform {
    /// The file name of the platform's plugin, as looked for in
    /// `RUXLA_PJRT_PLUGIN_DIR` and in the cache: `libpjrt_cpu.so`
    /// (`libpjrt_cpu.dylib` on macOS) or `xla_cuda_plugin.so`.
    pub fn plugin_file(self) -> &'static str {
        match self {
            Platform::Cpu => ruxla_pjrt::CPU_PLUGIN_FILE,
            Platform::Cuda => ruxla_pjrt::CUDA_PLUGIN_FILE,
        }
    }

    fn plugin_env(self) -> &'static str {
        match self {
            Platform::Cpu => "RUXLA_PJRT_CPU_PLUGIN",
            Platform::Cuda => "RUXLA_PJRT_CUDA_PLUGIN",
        }
    }
}

#[derive(Default)]
struct Config {
    platform: Option<Platform>,
    plugin_paths: HashMap<Platform, PathBuf>,
}

fn config() -> std::sync::MutexGuard<'static, Config> {
    static CONFIG: OnceLock<Mutex<Config>> = OnceLock::new();
    CONFIG
        .get_or_init(Default::default)
        .lock()
        .unwrap_or_else(PoisonError::into_inner)
}

/// Sets the platform for the rest of the process.
pub fn set_platform(platform: Platform) {
    config().platform = Some(platform);
}

/// Sets the path of the PJRT plugin of a platform.
pub fn set_plugin_path(platform: Platform, path: impl Into<PathBuf>) {
    config().plugin_paths.insert(platform, path.into());
}

/// Returns the platform that runs jitted functions (see the module
/// documentation).
///
/// # Panics
///
/// Panics if `RUXLA_PLATFORM` has an unknown value.
pub fn platform() -> Platform {
    let mut config = config();
    if let Some(platform) = config.platform {
        return platform;
    }
    let platform = match std::env::var("RUXLA_PLATFORM").as_deref() {
        Ok("cpu") | Err(_) => Platform::Cpu,
        Ok("cuda") => Platform::Cuda,
        Ok(other) => panic!("unknown RUXLA_PLATFORM `{other}`; expected cpu or cuda"),
    };
    config.platform = Some(platform);
    platform
}

fn plugin_path(platform: Platform) -> Option<PathBuf> {
    if let Some(path) = config().plugin_paths.get(&platform) {
        return Some(path.clone());
    }
    if let Some(path) = std::env::var_os(platform.plugin_env()) {
        return Some(PathBuf::from(path));
    }
    if let Some(dir) = std::env::var_os("RUXLA_PJRT_PLUGIN_DIR") {
        let path = PathBuf::from(dir).join(platform.plugin_file());
        if path.exists() {
            return Some(path);
        }
    }
    plugins::find(platform)
}

/// Returns the client of a platform, creating it on first use.
///
/// # Errors
///
/// Returns an error if the platform's plugin is not configured or fails to
/// load.
pub fn client(platform: Platform) -> Result<Client, Error> {
    static CLIENTS: OnceLock<Mutex<HashMap<Platform, Client>>> = OnceLock::new();
    let mut clients = CLIENTS
        .get_or_init(Default::default)
        .lock()
        .unwrap_or_else(PoisonError::into_inner);
    if let Some(client) = clients.get(&platform) {
        return Ok(client.clone());
    }
    let path = plugin_path(platform).ok_or(Error::NoPlugin(platform))?;
    let plugin = Plugin::load(&path)?;
    // The handlers of the custom calls that primitives without StableHLO
    // operations (linear algebra) lower to.
    let ffi_platform = match platform {
        Platform::Cpu => "Host",
        Platform::Cuda => "CUDA",
    };
    ruxla_pjrt::linalg::register_handlers(plugin, ffi_platform)?;
    let client = match platform {
        // Allocate GPU memory on demand instead of reserving most of it.
        Platform::Cuda => {
            plugin.client_with_options(&[ClientOption::bool("preallocate", false)])?
        }
        Platform::Cpu => plugin.client()?,
    };
    clients.insert(platform, client.clone());
    Ok(client)
}

/// The number of executables kept before the cache is emptied.
const CACHE_CAPACITY: usize = 1024;

/// Compiles a function for a platform, or returns the cached executable.
///
/// # Errors
///
/// Returns an error if the function cannot be lowered or compiled.
pub(crate) fn compile(platform: Platform, f: &Function) -> Result<Arc<LoadedExecutable>, Error> {
    compile_donating(platform, f, &[])
}

/// [`compile`], with the inputs marked `donated` given to the program for
/// reuse as outputs (see `ruxla_stablehlo::LowerOptions`).
pub(crate) fn compile_donating(
    platform: Platform,
    f: &Function,
    donated: &[bool],
) -> Result<Arc<LoadedExecutable>, Error> {
    type Cache = HashMap<(Platform, Vec<u8>, Vec<bool>), Arc<LoadedExecutable>>;
    static CACHE: OnceLock<Mutex<Cache>> = OnceLock::new();
    let cache = CACHE.get_or_init(Default::default);
    let key = (platform, ruxla_ir::serialize::to_bytes(f), donated.to_vec());
    if let Some(exe) = cache
        .lock()
        .unwrap_or_else(PoisonError::into_inner)
        .get(&key)
    {
        return Ok(exe.clone());
    }
    let client = client(platform)?;
    let options = ruxla_stablehlo::LowerOptions {
        target: Target::Pjrt,
        platform: match platform {
            Platform::Cpu => ruxla_ir::lowering::Platform::Cpu,
            Platform::Cuda => ruxla_ir::lowering::Platform::Gpu,
        },
        donated: donated.to_vec(),
    };
    let module = ruxla_stablehlo::lower_with(f, &options)?;
    let exe = Arc::new(client.compile(&module)?);
    let mut cache = cache.lock().unwrap_or_else(PoisonError::into_inner);
    if cache.len() >= CACHE_CAPACITY {
        cache.clear();
    }
    cache.insert(key, exe.clone());
    Ok(exe)
}