1use 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#[derive(Debug, thiserror::Error)]
45#[non_exhaustive]
46pub enum Error {
47 #[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 #[error("failed to lower to StableHLO: {0}")]
64 Lowering(#[from] ruxla_ir::Error),
65 #[error(transparent)]
67 Pjrt(#[from] ruxla_pjrt::Error),
68}
69
70#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
72#[non_exhaustive]
73pub enum Platform {
74 Cpu,
76 Cuda,
78}
79
80impl Platform {
81 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
113pub fn set_platform(platform: Platform) {
115 config().platform = Some(platform);
116}
117
118pub fn set_plugin_path(platform: Platform, path: impl Into<PathBuf>) {
120 config().plugin_paths.insert(platform, path.into());
121}
122
123pub 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
159pub 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 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 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
194const CACHE_CAPACITY: usize = 1024;
196
197pub(crate) fn compile(platform: Platform, f: &Function) -> Result<Arc<LoadedExecutable>, Error> {
203 compile_donating(platform, f, &[])
204}
205
206pub(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}