Skip to main content

ruxla_pjrt/
client.rs

1//! Clients and devices.
2
3use std::ffi::c_char;
4use std::fmt;
5use std::sync::Arc;
6
7use crate::api::{Api, call, new_args, string_from_raw};
8use crate::buffer::{Buffer, HostElement};
9use crate::compile_options::CompileOptions;
10use crate::error::{Error, Result};
11use crate::executable::LoadedExecutable;
12use crate::sys;
13
14/// A client of one platform (CPU, CUDA, ...).
15///
16/// A client owns the devices of its platform, compiles programs, and creates
17/// buffers. It is reference-counted, so clones are cheap and refer to the
18/// same client.
19#[derive(Clone)]
20pub struct Client {
21    pub(crate) inner: Arc<ClientInner>,
22}
23
24pub(crate) struct ClientInner {
25    pub(crate) api: Api,
26    pub(crate) raw: *mut sys::PJRT_Client,
27}
28
29// SAFETY: PJRT clients are thread-safe; the C API allows calling any client
30// function from any thread.
31unsafe impl Send for ClientInner {}
32// SAFETY: See above.
33unsafe impl Sync for ClientInner {}
34
35impl Drop for ClientInner {
36    fn drop(&mut self) {
37        let mut args = new_args!(sys::PJRT_Client_Destroy_Args);
38        args.client = self.raw;
39        // SAFETY: `raw` is a live client, and nothing refers to it any more:
40        // devices, buffers, and executables hold a reference to `ClientInner`.
41        // Errors cannot be reported from `drop`.
42        let _ = call!(self.api, PJRT_Client_Destroy, &mut args);
43    }
44}
45
46impl Client {
47    pub(crate) fn new(api: Api, options: &[ClientOption<'_>]) -> Result<Self> {
48        let raw_options: Vec<sys::PJRT_NamedValue> =
49            options.iter().copied().map(ClientOption::to_raw).collect();
50        let mut args = new_args!(sys::PJRT_Client_Create_Args);
51        args.create_options = raw_options.as_ptr();
52        args.num_options = raw_options.len();
53        // SAFETY: `args` is initialized, and the options borrow from `options`,
54        // which outlives the call.
55        call!(api, PJRT_Client_Create, &mut args)?;
56        Ok(Self {
57            inner: Arc::new(ClientInner {
58                api,
59                raw: args.client,
60            }),
61        })
62    }
63
64    fn api(&self) -> Api {
65        self.inner.api
66    }
67
68    /// Returns the name of the platform, such as `"cpu"` or `"cuda"`.
69    ///
70    /// # Errors
71    ///
72    /// Returns an error if the plugin fails to report the name.
73    pub fn platform_name(&self) -> Result<String> {
74        let mut args = new_args!(sys::PJRT_Client_PlatformName_Args);
75        args.client = self.inner.raw;
76        // SAFETY: `args` is initialized and the client is alive.
77        call!(self.api(), PJRT_Client_PlatformName, &mut args)?;
78        // SAFETY: The name is owned by the client, which is alive.
79        Ok(unsafe { string_from_raw(args.platform_name, args.platform_name_size) })
80    }
81
82    /// Returns the devices this client can use.
83    ///
84    /// # Errors
85    ///
86    /// Returns an error if the plugin fails to list the devices.
87    pub fn devices(&self) -> Result<Vec<Device>> {
88        let mut args = new_args!(sys::PJRT_Client_AddressableDevices_Args);
89        args.client = self.inner.raw;
90        // SAFETY: `args` is initialized and the client is alive.
91        call!(self.api(), PJRT_Client_AddressableDevices, &mut args)?;
92        if args.num_addressable_devices == 0 {
93            return Ok(Vec::new());
94        }
95        // SAFETY: The plugin returns an array of `num_addressable_devices`
96        // device pointers owned by the client.
97        let raw = unsafe {
98            std::slice::from_raw_parts(args.addressable_devices, args.num_addressable_devices)
99        };
100        Ok(raw
101            .iter()
102            .map(|&raw| Device {
103                client: self.clone(),
104                raw,
105            })
106            .collect())
107    }
108
109    /// Compiles a StableHLO program in the MLIR text format.
110    ///
111    /// The program must have a public function named `main`, which becomes
112    /// the entry point of the executable.
113    ///
114    /// # Errors
115    ///
116    /// Returns an error if the program cannot be parsed or compiled.
117    pub fn compile(&self, mlir: &str) -> Result<LoadedExecutable> {
118        self.compile_with_options(mlir, &CompileOptions::new())
119    }
120
121    /// Compiles a StableHLO program with the given options.
122    ///
123    /// # Errors
124    ///
125    /// Returns an error if the program cannot be parsed or compiled.
126    pub fn compile_with_options(
127        &self,
128        mlir: &str,
129        options: &CompileOptions,
130    ) -> Result<LoadedExecutable> {
131        const FORMAT: &str = "mlir";
132        let compile_options = options.encode();
133        let mut program = new_args!(sys::PJRT_Program);
134        // The C API takes `char*`, but does not modify the code.
135        program.code = mlir.as_ptr().cast::<c_char>().cast_mut();
136        program.code_size = mlir.len();
137        program.format = FORMAT.as_ptr().cast::<c_char>();
138        program.format_size = FORMAT.len();
139
140        let mut args = new_args!(sys::PJRT_Client_Compile_Args);
141        args.client = self.inner.raw;
142        args.program = &program;
143        args.compile_options = compile_options.as_ptr().cast::<c_char>();
144        args.compile_options_size = compile_options.len();
145        // SAFETY: `args` is initialized, the client is alive, and the program
146        // and options outlive the call.
147        call!(self.api(), PJRT_Client_Compile, &mut args)?;
148        // SAFETY: `executable` was just created by this client.
149        unsafe { LoadedExecutable::from_raw(self.clone(), args.executable) }
150    }
151
152    /// Copies host data to a new buffer on the first device.
153    ///
154    /// `dims` is the shape of the buffer in row-major order. Its product must
155    /// equal `data.len()`.
156    ///
157    /// # Errors
158    ///
159    /// Returns an error if the shape does not match the data, if the client
160    /// has no device, or if the transfer fails.
161    pub fn buffer_from_host<T: HostElement>(&self, data: &[T], dims: &[i64]) -> Result<Buffer> {
162        let device = self
163            .devices()?
164            .into_iter()
165            .next()
166            .ok_or_else(|| Error::HostBuffer(String::from("the client has no device")))?;
167        self.buffer_from_host_bytes(as_bytes(data), T::ELEMENT_TYPE, dims, &device)
168    }
169
170    /// Copies a host array to a new buffer on the first device.
171    ///
172    /// # Errors
173    ///
174    /// Returns an error if the client has no device or the transfer fails.
175    pub fn buffer_from_host_array(&self, array: &ruxla_ir::HostArray) -> Result<Buffer> {
176        let device = self
177            .devices()?
178            .into_iter()
179            .next()
180            .ok_or_else(|| Error::HostBuffer(String::from("the client has no device")))?;
181        let dims: Vec<i64> = array.shape().iter().map(|&d| d as i64).collect();
182        self.buffer_from_host_bytes(
183            &array.to_bytes(),
184            crate::ElementType::from_dtype(array.dtype()),
185            &dims,
186            &device,
187        )
188    }
189
190    /// Copies raw host bytes to a new buffer on `device`.
191    ///
192    /// `bytes` holds the elements in row-major order and native byte order.
193    ///
194    /// # Errors
195    ///
196    /// Returns an error if the size of `bytes` does not match `ty` and `dims`,
197    /// if `device` belongs to another client, or if the transfer fails.
198    pub fn buffer_from_host_bytes(
199        &self,
200        bytes: &[u8],
201        ty: crate::ElementType,
202        dims: &[i64],
203        device: &Device,
204    ) -> Result<Buffer> {
205        if !Arc::ptr_eq(&device.client.inner, &self.inner) {
206            return Err(Error::HostBuffer(String::from(
207                "the device belongs to another client",
208            )));
209        }
210        let elem_size = ty
211            .size_in_bytes()
212            .ok_or_else(|| Error::HostBuffer(format!("unsupported element type {ty:?}")))?;
213        let num_elements = dims
214            .iter()
215            .try_fold(1usize, |acc, &d| acc.checked_mul(usize::try_from(d).ok()?));
216        if num_elements.and_then(|n| n.checked_mul(elem_size)) != Some(bytes.len()) {
217            return Err(Error::HostBuffer(format!(
218                "{} bytes do not match shape {dims:?} of {ty:?}",
219                bytes.len()
220            )));
221        }
222
223        let mut args = new_args!(sys::PJRT_Client_BufferFromHostBuffer_Args);
224        args.client = self.inner.raw;
225        args.data = bytes.as_ptr().cast();
226        args.type_ = ty.to_raw();
227        args.dims = dims.as_ptr();
228        args.num_dims = dims.len();
229        // Copy the data during the call, so that `bytes` may be dropped as
230        // soon as this function returns.
231        args.host_buffer_semantics =
232            sys::PJRT_HostBufferSemantics::PJRT_HostBufferSemantics_kImmutableOnlyDuringCall;
233        args.device = device.raw;
234        // SAFETY: `args` is initialized, the client and device are alive, and
235        // `bytes` and `dims` outlive the call and match each other.
236        call!(self.api(), PJRT_Client_BufferFromHostBuffer, &mut args)?;
237        // SAFETY: The buffer was just created by this client.
238        let buffer = unsafe { Buffer::from_raw(self.clone(), args.buffer) };
239        // SAFETY: The event (if any) was just returned by this plugin.
240        unsafe { await_event(self.api(), args.done_with_host_buffer) }?;
241        Ok(buffer)
242    }
243}
244
245impl fmt::Debug for Client {
246    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
247        f.debug_struct("Client")
248            .field("platform", &self.platform_name().unwrap_or_default())
249            .finish_non_exhaustive()
250    }
251}
252
253/// A device of a [`Client`].
254#[derive(Clone)]
255pub struct Device {
256    client: Client,
257    raw: *mut sys::PJRT_Device,
258}
259
260// SAFETY: Device handles are owned by the client and may be used from any
261// thread, like the client itself.
262unsafe impl Send for Device {}
263// SAFETY: See above.
264unsafe impl Sync for Device {}
265
266impl Device {
267    /// Returns the kind of the device, such as `"cpu"` or
268    /// `"NVIDIA GeForce RTX 5090"`.
269    ///
270    /// # Errors
271    ///
272    /// Returns an error if the plugin fails to describe the device.
273    pub fn kind(&self) -> Result<String> {
274        let api = self.client.api();
275        let mut desc = new_args!(sys::PJRT_Device_GetDescription_Args);
276        desc.device = self.raw;
277        // SAFETY: `desc` is initialized and the device is alive.
278        call!(api, PJRT_Device_GetDescription, &mut desc)?;
279        let mut args = new_args!(sys::PJRT_DeviceDescription_Kind_Args);
280        args.device_description = desc.device_description;
281        // SAFETY: The description is owned by the device, which is alive.
282        call!(api, PJRT_DeviceDescription_Kind, &mut args)?;
283        // SAFETY: The kind is owned by the description.
284        Ok(unsafe { string_from_raw(args.device_kind, args.device_kind_size) })
285    }
286}
287
288impl fmt::Debug for Device {
289    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
290        f.debug_struct("Device")
291            .field("kind", &self.kind().unwrap_or_default())
292            .finish_non_exhaustive()
293    }
294}
295
296/// An option passed to [`Plugin::client_with_options`](crate::Plugin::client_with_options).
297#[derive(Clone, Copy, Debug)]
298pub struct ClientOption<'a> {
299    name: &'a str,
300    value: OptionValue<'a>,
301}
302
303#[derive(Clone, Copy, Debug)]
304enum OptionValue<'a> {
305    String(&'a str),
306    Int64(i64),
307    Int64List(&'a [i64]),
308    Float(f32),
309    Bool(bool),
310}
311
312impl<'a> ClientOption<'a> {
313    /// Creates a string option.
314    pub fn string(name: &'a str, value: &'a str) -> Self {
315        Self {
316            name,
317            value: OptionValue::String(value),
318        }
319    }
320
321    /// Creates an integer option.
322    pub fn int64(name: &'a str, value: i64) -> Self {
323        Self {
324            name,
325            value: OptionValue::Int64(value),
326        }
327    }
328
329    /// Creates an integer list option.
330    pub fn int64_list(name: &'a str, value: &'a [i64]) -> Self {
331        Self {
332            name,
333            value: OptionValue::Int64List(value),
334        }
335    }
336
337    /// Creates a floating point option.
338    pub fn float(name: &'a str, value: f32) -> Self {
339        Self {
340            name,
341            value: OptionValue::Float(value),
342        }
343    }
344
345    /// Creates a boolean option.
346    pub fn bool(name: &'a str, value: bool) -> Self {
347        Self {
348            name,
349            value: OptionValue::Bool(value),
350        }
351    }
352
353    /// Converts the option to the C representation, which borrows the name and
354    /// value of the option.
355    fn to_raw(self) -> sys::PJRT_NamedValue {
356        use sys::PJRT_NamedValue_Type as Ty;
357        let mut raw = new_args!(sys::PJRT_NamedValue);
358        raw.name = self.name.as_ptr().cast();
359        raw.name_size = self.name.len();
360        let (ty, size) = match self.value {
361            OptionValue::String(s) => {
362                raw.__bindgen_anon_1.string_value = s.as_ptr().cast();
363                (Ty::PJRT_NamedValue_kString, s.len())
364            }
365            OptionValue::Int64(v) => {
366                raw.__bindgen_anon_1.int64_value = v;
367                (Ty::PJRT_NamedValue_kInt64, 1)
368            }
369            OptionValue::Int64List(v) => {
370                raw.__bindgen_anon_1.int64_array_value = v.as_ptr();
371                (Ty::PJRT_NamedValue_kInt64List, v.len())
372            }
373            OptionValue::Float(v) => {
374                raw.__bindgen_anon_1.float_value = v;
375                (Ty::PJRT_NamedValue_kFloat, 1)
376            }
377            OptionValue::Bool(v) => {
378                raw.__bindgen_anon_1.bool_value = v;
379                (Ty::PJRT_NamedValue_kBool, 1)
380            }
381        };
382        raw.type_ = ty;
383        raw.value_size = size;
384        raw
385    }
386}
387
388/// Waits for an event and destroys it, returning the error it carries.
389///
390/// # Safety
391///
392/// `event` must be null or a live event of the plugin behind `api`, and must
393/// not be used after this call.
394pub(crate) unsafe fn await_event(api: Api, event: *mut sys::PJRT_Event) -> Result<()> {
395    if event.is_null() {
396        return Ok(());
397    }
398    let mut args = new_args!(sys::PJRT_Event_Await_Args);
399    args.event = event;
400    // SAFETY: `event` is live (caller's contract).
401    let result = call!(api, PJRT_Event_Await, &mut args);
402    let mut destroy = new_args!(sys::PJRT_Event_Destroy_Args);
403    destroy.event = event;
404    // SAFETY: `event` is live and is not used after this call.
405    let destroyed = call!(api, PJRT_Event_Destroy, &mut destroy);
406    result.and(destroyed)
407}
408
409/// Views a slice of host elements as bytes.
410pub(crate) fn as_bytes<T: HostElement>(data: &[T]) -> &[u8] {
411    // SAFETY: `HostElement` types are plain old data without padding, so all
412    // of their bytes are initialized.
413    unsafe { std::slice::from_raw_parts(data.as_ptr().cast::<u8>(), std::mem::size_of_val(data)) }
414}