use std::any::Any;
use std::collections::HashMap;
use std::fmt;
use std::sync::{Arc, Mutex, PoisonError};
use ruxla_ir::{AVal, Function, HostArray, Params};
use ruxla_pjrt::{Buffer, ExecuteOptions};
use crate::backend::{Backend, Native, Trace};
use crate::runtime::{self, Error, Platform};
use crate::trace::{self, TraceRef, trace_function};
use crate::transform::trace_with_output;
use crate::tree::{Tree, TreeDef, leaves};
pub fn jit<F>(f: F) -> Jit<F> {
Jit {
f,
name: String::from("jit"),
cache: Mutex::new(HashMap::new()),
skeletons: Mutex::new(HashMap::new()),
}
}
pub struct Jit<F> {
f: F,
name: String,
cache: Mutex<HashMap<(TreeDef, Vec<AVal>), Specialization>>,
skeletons: Mutex<HashMap<(TreeDef, Vec<AVal>), Specialization>>,
}
type Specialization = Arc<dyn Any + Send + Sync>;
impl<F> fmt::Debug for Jit<F> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Jit")
.field("name", &self.name)
.finish_non_exhaustive()
}
}
struct Compiled<O> {
function: Function,
out: O,
platform: Platform,
}
impl<F> Jit<F> {
pub fn with_name(mut self, name: impl Into<String>) -> Self {
self.name = name.into();
self
}
fn compiled<I, O>(&self, input: &I) -> Arc<Compiled<O>>
where
I: Tree<Native>,
O: Tree<Trace> + Send + Sync + 'static,
F: Fn(I::On<Trace>) -> O,
{
let avals: Vec<AVal> = leaves(input).iter().map(Native::leaf_aval).collect();
let key = (input.def(), avals);
let cached = self
.cache
.lock()
.unwrap_or_else(PoisonError::into_inner)
.get(&key)
.cloned();
if let Some(c) = cached.and_then(|c| c.downcast::<Compiled<O>>().ok()) {
return c;
}
let (traced, out) = trace_with_output(&self.f, input);
let compiled = Arc::new(Compiled {
function: traced.function,
out,
platform: runtime::platform(),
});
self.cache
.lock()
.unwrap_or_else(PoisonError::into_inner)
.insert(key, compiled.clone());
compiled
}
#[track_caller]
pub fn call<I, O>(&self, input: &I) -> O::On<Native>
where
I: Tree<Native>,
O: Tree<Trace> + Send + Sync + 'static,
F: Fn(I::On<Trace>) -> O,
{
self.try_call(input).unwrap_or_else(|e| panic!("{e}"))
}
pub fn try_call<I, O>(&self, input: &I) -> Result<O::On<Native>, Error>
where
I: Tree<Native>,
O: Tree<Trace> + Send + Sync + 'static,
F: Fn(I::On<Trace>) -> O,
{
let c = self.compiled::<I, O>(input);
let client = runtime::client(c.platform)?;
let buffers = leaves(input)
.iter()
.map(|a| client.buffer_from_host_array(a))
.collect::<Result<Vec<_>, _>>()?;
let outs = execute(&c, &buffers.iter().collect::<Vec<_>>())?;
let outs = outs
.iter()
.map(Buffer::to_host_array)
.collect::<Result<Vec<HostArray>, _>>()?;
Ok(c.out.rebuild::<Native>(&mut outs.into_iter()))
}
#[track_caller]
pub fn call_on_device<I, O>(&self, input: &OnDevice<I>) -> OnDevice<O::On<Native>>
where
I: Tree<Native>,
O: Tree<Trace> + Send + Sync + 'static,
O::On<Native>: Send + Sync + 'static,
F: Fn(I::On<Trace>) -> O,
{
let c = self.compiled::<I, O>(&input.skeleton);
assert_eq!(
c.platform, input.platform,
"the values are on another platform"
);
let args: Vec<&Buffer> = input.buffers.iter().map(Arc::as_ref).collect();
let exe = runtime::compile(c.platform, &c.function).unwrap_or_else(|e| panic!("{e}"));
let (outs, _done) = exe
.execute_with(&args, &ExecuteOptions::default())
.unwrap_or_else(|e| panic!("{e}"));
self.on_device(&c, &input.skeleton, outs)
}
#[track_caller]
pub fn call_on_device_donating<I, O>(&self, input: OnDevice<I>) -> OnDevice<O::On<Native>>
where
I: Tree<Native>,
O: Tree<Trace> + Send + Sync + 'static,
O::On<Native>: Send + Sync + 'static,
F: Fn(I::On<Trace>) -> O,
{
let c = self.compiled::<I, O>(&input.skeleton);
assert_eq!(
c.platform, input.platform,
"the values are on another platform"
);
let donated = vec![true; input.buffers.len()];
let exe = runtime::compile_donating(c.platform, &c.function, &donated)
.unwrap_or_else(|e| panic!("{e}"));
let options = ExecuteOptions {
non_donatable: input
.buffers
.iter()
.enumerate()
.filter(|(_, b)| Arc::strong_count(b) > 1)
.map(|(i, _)| i as i64)
.collect(),
};
let args: Vec<&Buffer> = input.buffers.iter().map(Arc::as_ref).collect();
let (outs, _done) = exe
.execute_with(&args, &options)
.unwrap_or_else(|e| panic!("{e}"));
self.on_device(&c, &input.skeleton, outs)
}
fn on_device<I, O>(
&self,
c: &Compiled<O>,
input: &I,
outs: Vec<Buffer>,
) -> OnDevice<O::On<Native>>
where
I: Tree<Native>,
O: Tree<Trace> + Send + Sync + 'static,
O::On<Native>: Send + Sync + 'static,
{
let avals: Vec<AVal> = leaves(input).iter().map(Native::leaf_aval).collect();
let key = (input.def(), avals);
let cached = self
.skeletons
.lock()
.unwrap_or_else(PoisonError::into_inner)
.get(&key)
.cloned()
.and_then(|s| s.downcast::<O::On<Native>>().ok());
let skeleton = match cached {
Some(s) => (*s).clone(),
None => {
let zeros: Vec<HostArray> = c
.function
.out_avals()
.iter()
.map(|a| HostArray::zeros(a.shape.clone(), a.dtype))
.collect();
let s = c.out.rebuild::<Native>(&mut zeros.into_iter());
self.skeletons
.lock()
.unwrap_or_else(PoisonError::into_inner)
.insert(key, Arc::new(s.clone()));
s
}
};
OnDevice {
skeleton,
buffers: outs.into_iter().map(Arc::new).collect(),
platform: c.platform,
}
}
pub fn call_traced<I, O>(&self, input: I) -> O
where
I: Tree<Trace>,
O: Tree<Trace>,
F: Fn(I) -> O,
{
let args = leaves(&input);
let in_avals: Vec<AVal> = args.iter().map(|&r| trace::aval(r)).collect();
let mut out: Option<O> = None;
let traced = trace_function(&in_avals, |refs| {
let o = (self.f)(input.unflatten_like(&mut refs.iter().copied()));
let l = leaves(&o);
out = Some(o);
l
});
let mut inputs: Vec<TraceRef> = traced.captured;
inputs.extend(args);
let outs = trace::bind(
ruxla_prims::JIT,
&inputs,
Params::Jit {
name: self.name.clone(),
body: Arc::new(traced.function),
},
);
out.expect("the function was called")
.unflatten_like(&mut outs.into_iter())
}
}
fn execute<O>(c: &Compiled<O>, args: &[&Buffer]) -> Result<Vec<Buffer>, Error> {
let exe = runtime::compile(c.platform, &c.function)?;
Ok(exe.execute(args)?)
}
pub struct OnDevice<T> {
skeleton: T,
buffers: Vec<Arc<Buffer>>,
platform: Platform,
}
impl<T: Clone> Clone for OnDevice<T> {
fn clone(&self) -> Self {
Self {
skeleton: self.skeleton.clone(),
buffers: self.buffers.clone(),
platform: self.platform,
}
}
}
impl<T> fmt::Debug for OnDevice<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("OnDevice")
.field("platform", &self.platform)
.field("leaves", &self.buffers.len())
.finish_non_exhaustive()
}
}
impl<T: Tree<Native>> OnDevice<T> {
pub fn to_native(&self) -> T {
let host: Vec<HostArray> = self
.buffers
.iter()
.map(|b| b.to_host_array().unwrap_or_else(|e| panic!("{e}")))
.collect();
self.skeleton.unflatten_like(&mut host.into_iter())
}
}
pub fn device_put<T: Tree<Native>>(x: &T) -> OnDevice<T> {
let platform = runtime::platform();
let client = runtime::client(platform).unwrap_or_else(|e| panic!("{e}"));
let buffers = leaves(x)
.iter()
.map(|a| {
client
.buffer_from_host_array(a)
.map(Arc::new)
.unwrap_or_else(|e| panic!("{e}"))
})
.collect();
OnDevice {
skeleton: x.clone(),
buffers,
platform,
}
}