Skip to main content

ruxla_pjrt/
plugin.rs

1//! Loading PJRT plugins.
2
3use std::collections::HashMap;
4use std::fmt;
5use std::path::{Path, PathBuf};
6use std::sync::{Mutex, OnceLock};
7
8use crate::api::{Api, call, new_args};
9use crate::client::{Client, ClientOption};
10use crate::error::{Error, Result};
11use crate::sys;
12
13/// A loaded PJRT plugin.
14///
15/// A plugin is a shared library that implements the PJRT C API for one kind
16/// of hardware, such as `libpjrt_cpu.so` for CPUs or `xla_cuda_plugin.so` for
17/// NVIDIA GPUs.
18///
19/// Plugins stay loaded until the process exits, because PJRT plugins do not
20/// support being unloaded. Loading the same path twice returns the same
21/// plugin, so `Plugin` is a cheap, copyable handle.
22#[derive(Clone, Copy)]
23pub struct Plugin {
24    api: Api,
25}
26
27impl Plugin {
28    /// Loads the plugin at `path` and initializes it.
29    ///
30    /// # Errors
31    ///
32    /// Returns an error if the shared library cannot be loaded, if it does not
33    /// export `GetPjrtApi`, or if the plugin fails to initialize.
34    pub fn load(path: impl AsRef<Path>) -> Result<Self> {
35        static LOADED: OnceLock<Mutex<HashMap<PathBuf, Plugin>>> = OnceLock::new();
36
37        let path = path.as_ref();
38        let key = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());
39        // cuSOLVER may be next to it (the JAX CUDA plugin's libraries).
40        crate::cusolver::note_plugin_path(key.clone());
41        let mut loaded = LOADED
42            .get_or_init(Default::default)
43            .lock()
44            .unwrap_or_else(|e| e.into_inner());
45        if let Some(plugin) = loaded.get(&key) {
46            return Ok(*plugin);
47        }
48
49        let load_error = |source| Error::Load {
50            path: path.to_path_buf(),
51            source,
52        };
53        // SAFETY: Loading a shared library runs its initializers. PJRT plugins
54        // are trusted native code, and the caller chose to load this one.
55        let library = unsafe { libloading::Library::new(path) }.map_err(load_error)?;
56        // SAFETY: `GetPjrtApi` has this signature in every PJRT plugin.
57        let get_api = unsafe {
58            library.get::<unsafe extern "C" fn() -> *const sys::PJRT_Api>(b"GetPjrtApi\0")
59        }
60        .map_err(load_error)?;
61        // SAFETY: `GetPjrtApi` takes no arguments and returns a pointer to a
62        // static function table.
63        let raw = unsafe { get_api() };
64        // Keep the library loaded for the rest of the process, so that the
65        // function table stays valid.
66        std::mem::forget(library);
67        // SAFETY: The plugin returns a pointer to a table that lives as long as
68        // the library, which is never unloaded.
69        let raw = unsafe { raw.as_ref() }.ok_or_else(|| Error::Pjrt {
70            code: crate::ErrorCode::Internal,
71            message: String::from("GetPjrtApi returned null"),
72        })?;
73
74        let plugin = Plugin { api: Api::new(raw) };
75        plugin.initialize()?;
76        loaded.insert(key, plugin);
77        Ok(plugin)
78    }
79
80    fn initialize(self) -> Result<()> {
81        let mut args = new_args!(sys::PJRT_Plugin_Initialize_Args);
82        match call!(self.api, PJRT_Plugin_Initialize, &mut args) {
83            // Old plugins do not need to be initialized.
84            Err(Error::MissingFunction(_)) => Ok(()),
85            result => result,
86        }
87    }
88
89    pub(crate) fn api(self) -> Api {
90        self.api
91    }
92
93    /// Returns the version of the PJRT C API the plugin implements, as
94    /// `(major, minor)`.
95    pub fn api_version(self) -> (i32, i32) {
96        self.api.version()
97    }
98
99    /// Creates a client with the plugin's default options.
100    ///
101    /// # Errors
102    ///
103    /// Returns an error if the plugin fails to create a client, for example
104    /// because no device is available.
105    pub fn client(self) -> Result<Client> {
106        Client::new(self.api, &[])
107    }
108
109    /// Creates a client with platform-specific options.
110    ///
111    /// The available options depend on the plugin. For example, the CUDA
112    /// plugin accepts `preallocate` (a boolean) and `memory_fraction` (a
113    /// float).
114    ///
115    /// # Errors
116    ///
117    /// Returns an error if the plugin rejects an option or fails to create a
118    /// client.
119    pub fn client_with_options(self, options: &[ClientOption<'_>]) -> Result<Client> {
120        Client::new(self.api, options)
121    }
122}
123
124impl fmt::Debug for Plugin {
125    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
126        let (major, minor) = self.api_version();
127        f.debug_struct("Plugin")
128            .field("api_version", &format_args!("{major}.{minor}"))
129            .finish_non_exhaustive()
130    }
131}