Skip to main content

ruxla_pjrt/
executable.rs

1//! Compiled executables.
2
3use std::fmt;
4
5use crate::api::{call, new_args};
6use crate::buffer::Buffer;
7use crate::client::{Client, await_event};
8use crate::error::{Error, Result};
9use crate::sys;
10
11/// A program compiled for and loaded on the devices of a [`Client`].
12pub struct LoadedExecutable {
13    client: Client,
14    raw: *mut sys::PJRT_LoadedExecutable,
15    num_outputs: usize,
16}
17
18// SAFETY: PJRT executables are thread-safe and may be executed concurrently.
19unsafe impl Send for LoadedExecutable {}
20// SAFETY: See above.
21unsafe impl Sync for LoadedExecutable {}
22
23impl Drop for LoadedExecutable {
24    fn drop(&mut self) {
25        let mut args = new_args!(sys::PJRT_LoadedExecutable_Destroy_Args);
26        args.executable = self.raw;
27        // SAFETY: `raw` is live and owned by `self`. Errors cannot be reported
28        // from `drop`.
29        let _ = call!(
30            self.client.inner.api,
31            PJRT_LoadedExecutable_Destroy,
32            &mut args
33        );
34    }
35}
36
37impl LoadedExecutable {
38    /// Wraps a raw executable and queries its number of outputs.
39    ///
40    /// # Safety
41    ///
42    /// `raw` must be a live executable created by `client`, and ownership of
43    /// it is transferred to the returned value.
44    pub(crate) unsafe fn from_raw(
45        client: Client,
46        raw: *mut sys::PJRT_LoadedExecutable,
47    ) -> Result<Self> {
48        let api = client.inner.api;
49        // Construct `Self` first, so that `raw` is destroyed on error.
50        let mut exe = Self {
51            client,
52            raw,
53            num_outputs: 0,
54        };
55
56        let mut get = new_args!(sys::PJRT_LoadedExecutable_GetExecutable_Args);
57        get.loaded_executable = raw;
58        // SAFETY: `get` is initialized and `raw` is alive.
59        call!(api, PJRT_LoadedExecutable_GetExecutable, &mut get)?;
60
61        let mut num = new_args!(sys::PJRT_Executable_NumOutputs_Args);
62        num.executable = get.executable;
63        // SAFETY: `get.executable` was just returned and is alive.
64        let result = call!(api, PJRT_Executable_NumOutputs, &mut num);
65
66        // `GetExecutable` returns a new reference that the caller must destroy.
67        let mut destroy = new_args!(sys::PJRT_Executable_Destroy_Args);
68        destroy.executable = get.executable;
69        // SAFETY: `get.executable` is alive and not used after this call.
70        call!(api, PJRT_Executable_Destroy, &mut destroy)?;
71
72        result?;
73        exe.num_outputs = num.num_outputs;
74        Ok(exe)
75    }
76
77    /// Returns the number of outputs of the program.
78    pub fn num_outputs(&self) -> usize {
79        self.num_outputs
80    }
81
82    /// Runs the program on the first device and waits for it to finish.
83    ///
84    /// The arguments must be on the device the program runs on, and must
85    /// match the parameters of the program's `main` function.
86    ///
87    /// # Errors
88    ///
89    /// Returns an error if an argument belongs to another client or if the
90    /// execution fails.
91    pub fn execute(&self, args: &[&Buffer]) -> Result<Vec<Buffer>> {
92        let (outputs, done) = self.execute_with(args, &ExecuteOptions::default())?;
93        done.wait()?;
94        Ok(outputs)
95    }
96
97    /// Starts the program on the first device and returns its outputs
98    /// without waiting for it to finish, with an event that completes when
99    /// it does. The outputs can be passed to further executions (which the
100    /// device runs in order) or copied to the host (which waits for them).
101    ///
102    /// Arguments that the program aliases with outputs (donated, see
103    /// [`ExecuteOptions`]) are consumed: their buffers are deleted.
104    ///
105    /// # Errors
106    ///
107    /// Returns an error if an argument belongs to another client or if the
108    /// execution cannot start; errors during the execution are reported by
109    /// the event and by the outputs.
110    pub fn execute_with(
111        &self,
112        args: &[&Buffer],
113        options: &ExecuteOptions,
114    ) -> Result<(Vec<Buffer>, Event)> {
115        let api = self.client.inner.api;
116        if args.iter().any(|b| !b.belongs_to(&self.client)) {
117            return Err(Error::HostBuffer(String::from(
118                "an argument belongs to another client",
119            )));
120        }
121        let arg_list: Vec<*mut sys::PJRT_Buffer> = args.iter().map(|b| b.raw).collect();
122        let arg_lists = [arg_list.as_ptr()];
123        let mut out_list: Vec<*mut sys::PJRT_Buffer> = vec![std::ptr::null_mut(); self.num_outputs];
124        let out_lists = [out_list.as_mut_ptr()];
125        let mut events = [std::ptr::null_mut::<sys::PJRT_Event>()];
126
127        let mut raw_options = new_args!(sys::PJRT_ExecuteOptions);
128        raw_options.non_donatable_input_indices = options.non_donatable.as_ptr();
129        raw_options.num_non_donatable_input_indices = options.non_donatable.len();
130        let mut exec = new_args!(sys::PJRT_LoadedExecutable_Execute_Args);
131        exec.executable = self.raw;
132        exec.options = &mut raw_options;
133        exec.argument_lists = arg_lists.as_ptr();
134        exec.num_devices = 1;
135        exec.num_args = arg_list.len();
136        exec.output_lists = out_lists.as_ptr();
137        exec.device_complete_events = events.as_mut_ptr();
138        // SAFETY: `exec` is initialized; the executable, the argument buffers,
139        // the options (and the list of non-donatable indices they point to),
140        // and the argument and output arrays are alive for the call, and the
141        // output array has room for `num_outputs` buffers.
142        call!(api, PJRT_LoadedExecutable_Execute, &mut exec)?;
143
144        // Take ownership of the outputs and the event first, so that they
145        // are destroyed even if the execution failed.
146        let outputs: Vec<Buffer> = out_list
147            .iter()
148            .filter(|raw| !raw.is_null())
149            // SAFETY: The outputs were just created by this client.
150            .map(|&raw| unsafe { Buffer::from_raw(self.client.clone(), raw) })
151            .collect();
152        let event = Event {
153            client: self.client.clone(),
154            raw: events[0],
155        };
156        if outputs.len() != self.num_outputs {
157            return Err(Error::Pjrt {
158                code: crate::ErrorCode::Internal,
159                message: String::from("execution returned a null buffer"),
160            });
161        }
162        Ok((outputs, event))
163    }
164}
165
166/// Options of [`LoadedExecutable::execute_with`].
167#[derive(Clone, Debug, Default)]
168pub struct ExecuteOptions {
169    /// Arguments that must not be donated even if the program aliases them
170    /// with outputs (their contents are then copied).
171    pub non_donatable: Vec<i64>,
172}
173
174/// The completion of an execution ([`LoadedExecutable::execute_with`]).
175pub struct Event {
176    client: Client,
177    raw: *mut sys::PJRT_Event,
178}
179
180// SAFETY: PJRT events may be awaited and destroyed from any thread.
181unsafe impl Send for Event {}
182
183impl Event {
184    /// Waits for the execution to finish.
185    ///
186    /// # Errors
187    ///
188    /// Returns the error of the execution, if it failed.
189    pub fn wait(mut self) -> Result<()> {
190        let raw = std::mem::replace(&mut self.raw, std::ptr::null_mut());
191        // SAFETY: The event was returned by this plugin and is awaited and
192        // destroyed once (it is no longer owned by `self`).
193        unsafe { await_event(self.client.inner.api, raw) }
194    }
195}
196
197impl Drop for Event {
198    fn drop(&mut self) {
199        if self.raw.is_null() {
200            return;
201        }
202        let mut args = new_args!(sys::PJRT_Event_Destroy_Args);
203        args.event = self.raw;
204        // SAFETY: `raw` is live and owned by `self`. Errors cannot be reported
205        // from `drop`.
206        let _ = call!(self.client.inner.api, PJRT_Event_Destroy, &mut args);
207    }
208}
209
210impl fmt::Debug for Event {
211    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
212        f.debug_struct("Event").finish_non_exhaustive()
213    }
214}
215
216impl fmt::Debug for LoadedExecutable {
217    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
218        f.debug_struct("LoadedExecutable")
219            .field("num_outputs", &self.num_outputs)
220            .finish_non_exhaustive()
221    }
222}