Skip to main content

ruxla_pjrt/
buffer.rs

1//! Device buffers.
2
3use std::fmt;
4
5use crate::api::{call, new_args};
6use crate::client::{Client, await_event};
7use crate::element_type::ElementType;
8use crate::error::{Error, Result};
9use crate::sys;
10
11/// A Rust type that can be copied to and from a [`Buffer`] as is.
12///
13/// # Safety
14///
15/// Implementors must be plain old data without padding whose in-memory
16/// representation matches [`HostElement::ELEMENT_TYPE`], and every bit
17/// pattern of that size must be a valid value.
18pub unsafe trait HostElement: Copy + 'static {
19    /// The matching element type.
20    const ELEMENT_TYPE: ElementType;
21}
22
23macro_rules! host_element {
24    ($($ty:ty => $elem:ident),* $(,)?) => {$(
25        // SAFETY: Primitive numeric types are padding-free and every bit
26        // pattern is valid.
27        unsafe impl HostElement for $ty {
28            const ELEMENT_TYPE: ElementType = ElementType::$elem;
29        }
30    )*};
31}
32
33host_element! {
34    i8 => S8, i16 => S16, i32 => S32, i64 => S64,
35    u8 => U8, u16 => U16, u32 => U32, u64 => U64,
36    f32 => F32, f64 => F64,
37}
38
39/// An array stored on a device.
40///
41/// Buffers are created by [`Client::buffer_from_host`] and by executing a
42/// [`LoadedExecutable`](crate::LoadedExecutable).
43pub struct Buffer {
44    client: Client,
45    pub(crate) raw: *mut sys::PJRT_Buffer,
46}
47
48// SAFETY: PJRT buffers are thread-safe.
49unsafe impl Send for Buffer {}
50// SAFETY: See above.
51unsafe impl Sync for Buffer {}
52
53impl Drop for Buffer {
54    fn drop(&mut self) {
55        let mut args = new_args!(sys::PJRT_Buffer_Destroy_Args);
56        args.buffer = self.raw;
57        // SAFETY: `raw` is live and owned by `self`. Errors cannot be reported
58        // from `drop`.
59        let _ = call!(self.client.inner.api, PJRT_Buffer_Destroy, &mut args);
60    }
61}
62
63impl Buffer {
64    /// Wraps a raw buffer.
65    ///
66    /// # Safety
67    ///
68    /// `raw` must be a live buffer created by `client`, and ownership of it is
69    /// transferred to the returned value.
70    pub(crate) unsafe fn from_raw(client: Client, raw: *mut sys::PJRT_Buffer) -> Self {
71        Self { client, raw }
72    }
73
74    /// Returns whether the buffer was created by `client`.
75    pub(crate) fn belongs_to(&self, client: &Client) -> bool {
76        std::sync::Arc::ptr_eq(&self.client.inner, &client.inner)
77    }
78
79    /// Returns whether the buffer was deleted (donated to an execution).
80    ///
81    /// # Errors
82    ///
83    /// Returns an error if the plugin fails to report it.
84    pub fn is_deleted(&self) -> Result<bool> {
85        let mut args = new_args!(sys::PJRT_Buffer_IsDeleted_Args);
86        args.buffer = self.raw;
87        // SAFETY: `args` is initialized and the buffer is alive.
88        call!(self.client.inner.api, PJRT_Buffer_IsDeleted, &mut args)?;
89        Ok(args.is_deleted)
90    }
91
92    /// Returns the element type.
93    ///
94    /// # Errors
95    ///
96    /// Returns an error if the plugin fails to report the type.
97    pub fn element_type(&self) -> Result<ElementType> {
98        let mut args = new_args!(sys::PJRT_Buffer_ElementType_Args);
99        args.buffer = self.raw;
100        // SAFETY: `args` is initialized and the buffer is alive.
101        call!(self.client.inner.api, PJRT_Buffer_ElementType, &mut args)?;
102        Ok(ElementType::from_raw(args.type_))
103    }
104
105    /// Returns the shape.
106    ///
107    /// # Errors
108    ///
109    /// Returns an error if the plugin fails to report the shape.
110    pub fn dims(&self) -> Result<Vec<i64>> {
111        let mut args = new_args!(sys::PJRT_Buffer_Dimensions_Args);
112        args.buffer = self.raw;
113        // SAFETY: `args` is initialized and the buffer is alive.
114        call!(self.client.inner.api, PJRT_Buffer_Dimensions, &mut args)?;
115        if args.num_dims == 0 {
116            return Ok(Vec::new());
117        }
118        // SAFETY: The plugin returns `num_dims` sizes owned by the buffer.
119        Ok(unsafe { std::slice::from_raw_parts(args.dims, args.num_dims) }.to_vec())
120    }
121
122    /// Copies the contents to the host as raw bytes in row-major order.
123    ///
124    /// # Errors
125    ///
126    /// Returns an error if the transfer fails.
127    pub fn to_bytes(&self) -> Result<Vec<u8>> {
128        let api = self.client.inner.api;
129        // A first call without a destination returns the required size.
130        let mut args = new_args!(sys::PJRT_Buffer_ToHostBuffer_Args);
131        args.src = self.raw;
132        // SAFETY: `args` is initialized and the buffer is alive.
133        call!(api, PJRT_Buffer_ToHostBuffer, &mut args)?;
134
135        let mut bytes = vec![0u8; args.dst_size];
136        let mut args = new_args!(sys::PJRT_Buffer_ToHostBuffer_Args);
137        args.src = self.raw;
138        args.dst = bytes.as_mut_ptr().cast();
139        args.dst_size = bytes.len();
140        // SAFETY: `args` is initialized, the buffer is alive, and `bytes` is
141        // large enough and outlives the transfer, which we wait for below.
142        call!(api, PJRT_Buffer_ToHostBuffer, &mut args)?;
143        // SAFETY: The event was just returned by this plugin.
144        unsafe { await_event(api, args.event) }?;
145        Ok(bytes)
146    }
147
148    /// Copies the contents to a host array.
149    ///
150    /// # Errors
151    ///
152    /// Returns an error if the element type has no ruxla dtype, or if the
153    /// transfer fails.
154    pub fn to_host_array(&self) -> Result<ruxla_ir::HostArray> {
155        let ty = self.element_type()?;
156        let dtype = ty
157            .to_dtype()
158            .ok_or_else(|| Error::HostBuffer(format!("unsupported element type {ty:?}")))?;
159        let dims: Vec<usize> = self.dims()?.iter().map(|&d| d as usize).collect();
160        ruxla_ir::HostArray::from_bytes(&self.to_bytes()?, dims, dtype)
161            .map_err(|e| Error::HostBuffer(e.to_string()))
162    }
163
164    /// Copies the contents to the host as a vector of `T` in row-major order.
165    ///
166    /// # Errors
167    ///
168    /// Returns an error if `T` does not match the element type of the buffer,
169    /// or if the transfer fails.
170    pub fn to_vec<T: HostElement>(&self) -> Result<Vec<T>> {
171        let ty = self.element_type()?;
172        if ty != T::ELEMENT_TYPE {
173            return Err(Error::HostBuffer(format!(
174                "cannot read a buffer of {ty:?} as {:?}",
175                T::ELEMENT_TYPE
176            )));
177        }
178        let bytes = self.to_bytes()?;
179        let elem_size = std::mem::size_of::<T>();
180        Ok(bytes
181            .chunks_exact(elem_size)
182            // SAFETY: Each chunk has the size of `T`, and every bit pattern is
183            // a valid `T` (`HostElement` contract). The read is unaligned
184            // because `Vec<u8>` is only byte-aligned.
185            .map(|chunk| unsafe { chunk.as_ptr().cast::<T>().read_unaligned() })
186            .collect())
187    }
188}
189
190impl fmt::Debug for Buffer {
191    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
192        f.debug_struct("Buffer")
193            .field("element_type", &self.element_type().ok())
194            .field("dims", &self.dims().ok())
195            .finish_non_exhaustive()
196    }
197}