1use 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#[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
29unsafe impl Send for ClientInner {}
32unsafe 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 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 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 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 call!(self.api(), PJRT_Client_PlatformName, &mut args)?;
78 Ok(unsafe { string_from_raw(args.platform_name, args.platform_name_size) })
80 }
81
82 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 call!(self.api(), PJRT_Client_AddressableDevices, &mut args)?;
92 if args.num_addressable_devices == 0 {
93 return Ok(Vec::new());
94 }
95 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 pub fn compile(&self, mlir: &str) -> Result<LoadedExecutable> {
118 self.compile_with_options(mlir, &CompileOptions::new())
119 }
120
121 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 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 call!(self.api(), PJRT_Client_Compile, &mut args)?;
148 unsafe { LoadedExecutable::from_raw(self.clone(), args.executable) }
150 }
151
152 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 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 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 args.host_buffer_semantics =
232 sys::PJRT_HostBufferSemantics::PJRT_HostBufferSemantics_kImmutableOnlyDuringCall;
233 args.device = device.raw;
234 call!(self.api(), PJRT_Client_BufferFromHostBuffer, &mut args)?;
237 let buffer = unsafe { Buffer::from_raw(self.clone(), args.buffer) };
239 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#[derive(Clone)]
255pub struct Device {
256 client: Client,
257 raw: *mut sys::PJRT_Device,
258}
259
260unsafe impl Send for Device {}
263unsafe impl Sync for Device {}
265
266impl Device {
267 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 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 call!(api, PJRT_DeviceDescription_Kind, &mut args)?;
283 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#[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 pub fn string(name: &'a str, value: &'a str) -> Self {
315 Self {
316 name,
317 value: OptionValue::String(value),
318 }
319 }
320
321 pub fn int64(name: &'a str, value: i64) -> Self {
323 Self {
324 name,
325 value: OptionValue::Int64(value),
326 }
327 }
328
329 pub fn int64_list(name: &'a str, value: &'a [i64]) -> Self {
331 Self {
332 name,
333 value: OptionValue::Int64List(value),
334 }
335 }
336
337 pub fn float(name: &'a str, value: f32) -> Self {
339 Self {
340 name,
341 value: OptionValue::Float(value),
342 }
343 }
344
345 pub fn bool(name: &'a str, value: bool) -> Self {
347 Self {
348 name,
349 value: OptionValue::Bool(value),
350 }
351 }
352
353 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
388pub(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 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 let destroyed = call!(api, PJRT_Event_Destroy, &mut destroy);
406 result.and(destroyed)
407}
408
409pub(crate) fn as_bytes<T: HostElement>(data: &[T]) -> &[u8] {
411 unsafe { std::slice::from_raw_parts(data.as_ptr().cast::<u8>(), std::mem::size_of_val(data)) }
414}