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;
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
#[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),
#[error("failed to lower to StableHLO: {0}")]
Lowering(#[from] ruxla_ir::Error),
#[error(transparent)]
Pjrt(#[from] ruxla_pjrt::Error),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Platform {
Cpu,
Cuda,
}
impl Platform {
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)
}
pub fn set_platform(platform: Platform) {
config().platform = Some(platform);
}
pub fn set_plugin_path(platform: Platform, path: impl Into<PathBuf>) {
config().plugin_paths.insert(platform, path.into());
}
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)
}
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)?;
let ffi_platform = match platform {
Platform::Cpu => "Host",
Platform::Cuda => "CUDA",
};
ruxla_pjrt::linalg::register_handlers(plugin, ffi_platform)?;
let client = match platform {
Platform::Cuda => {
plugin.client_with_options(&[ClientOption::bool("preallocate", false)])?
}
Platform::Cpu => plugin.client()?,
};
clients.insert(platform, client.clone());
Ok(client)
}
const CACHE_CAPACITY: usize = 1024;
pub(crate) fn compile(platform: Platform, f: &Function) -> Result<Arc<LoadedExecutable>, Error> {
compile_donating(platform, f, &[])
}
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)
}