use std::fmt;
use std::sync::Arc;
use ruxla_ir::{AVal, HostArray, Params};
use ruxla_pjrt::Buffer;
use crate::backend::{Native, Trace};
use crate::runtime::{self, Error};
use crate::trace::{self, TraceRef, trace_function};
use crate::transform::trace_with_output;
use crate::tree::{Tree, leaves};
pub fn vmap<F>(f: F) -> Vmap<F> {
Vmap { f }
}
pub struct Vmap<F> {
f: F,
}
impl<F> fmt::Debug for Vmap<F> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Vmap").finish_non_exhaustive()
}
}
struct Batched<O> {
function: ruxla_ir::Function,
args: Vec<HostArray>,
out: O,
size: usize,
}
fn stack(xs: &[HostArray]) -> HostArray {
let first = &xs[0];
let mut bytes = Vec::with_capacity(first.to_bytes().len() * xs.len());
for x in xs {
assert_eq!(
x.aval(),
first.aval(),
"vmap: the examples must have the same types"
);
bytes.extend(x.to_bytes());
}
let mut shape = vec![xs.len()];
shape.extend_from_slice(first.shape());
HostArray::from_bytes(&bytes, shape, first.dtype()).expect("consistent sizes")
}
fn unstack(x: &HostArray, i: usize) -> HostArray {
let shape = x.shape()[1..].to_vec();
let n: usize = shape.iter().product::<usize>() * x.dtype().size_in_bytes();
HostArray::from_bytes(&x.to_bytes()[i * n..(i + 1) * n], shape, x.dtype())
.expect("consistent sizes")
}
impl<F> Vmap<F> {
fn batch<I, O>(&self, examples: &[I]) -> Batched<O>
where
I: Tree<Native>,
O: Tree<Trace>,
F: Fn(I::On<Trace>) -> O,
{
assert!(!examples.is_empty(), "vmap needs at least one example");
let (traced, out) = trace_with_output(&self.f, &examples[0]);
let per_example: Vec<Vec<HostArray>> = examples
.iter()
.map(|e| {
assert_eq!(
e.def(),
traced.in_def,
"vmap: the examples must have the same structure"
);
leaves(e)
})
.collect();
let args = (0..per_example[0].len())
.map(|j| stack(&per_example.iter().map(|l| l[j].clone()).collect::<Vec<_>>()))
.collect();
let n = examples.len();
let in_axes = vec![Some(0); traced.function.invars.len()];
let out_axes = vec![Some(0); traced.function.outvars.len()];
let function =
ruxla_transforms::vmap_with_out_axes(&traced.function, &in_axes, &out_axes, n)
.unwrap_or_else(|e| panic!("vmap: {e}"));
Batched {
function,
args,
out,
size: n,
}
}
fn unbatch<O: Tree<Trace>>(b: &Batched<O>, outs: &[HostArray]) -> Vec<O::On<Native>> {
(0..b.size)
.map(|i| {
let leaves: Vec<HostArray> = outs.iter().map(|x| unstack(x, i)).collect();
b.out.rebuild::<Native>(&mut leaves.into_iter())
})
.collect()
}
pub fn call<I, O>(&self, examples: &[I]) -> Vec<O::On<Native>>
where
I: Tree<Native>,
O: Tree<Trace>,
F: Fn(I::On<Trace>) -> O,
{
let b = self.batch(examples);
let outs = ruxla_interp::eval(&b.function, &b.args).unwrap_or_else(|e| panic!("{e}"));
Self::unbatch(&b, &outs)
}
pub fn call_xla<I, O>(&self, examples: &[I]) -> Result<Vec<O::On<Native>>, Error>
where
I: Tree<Native>,
O: Tree<Trace>,
F: Fn(I::On<Trace>) -> O,
{
let b = self.batch(examples);
let platform = runtime::platform();
let client = runtime::client(platform)?;
let exe = runtime::compile(platform, &b.function)?;
let buffers = b
.args
.iter()
.map(|a| client.buffer_from_host_array(a))
.collect::<Result<Vec<_>, _>>()?;
let outs = exe.execute(&buffers.iter().collect::<Vec<_>>())?;
let outs = outs
.iter()
.map(Buffer::to_host_array)
.collect::<Result<Vec<HostArray>, _>>()?;
Ok(Self::unbatch(&b, &outs))
}
pub fn call_traced<I, O>(&self, examples: I) -> O
where
I: Tree<Trace>,
O: Tree<Trace>,
F: Fn(I) -> O,
{
let args: Vec<TraceRef> = leaves(&examples);
let avals: Vec<AVal> = args.iter().map(|&r| trace::aval(r)).collect();
let n = avals
.first()
.and_then(|a| a.shape.first().copied())
.expect("vmap needs an input array with a leading dimension");
let in_avals: Vec<AVal> = avals
.iter()
.map(|a| {
assert_eq!(
a.shape.first(),
Some(&n),
"vmap: the inputs must have the same leading dimension"
);
AVal::new(a.shape[1..].to_vec(), a.dtype)
})
.collect();
let mut out: Option<O> = None;
let traced = trace_function(&in_avals, |refs| {
let o = (self.f)(examples.unflatten_like(&mut refs.iter().copied()));
let l = leaves(&o);
out = Some(o);
l
});
let ncap = traced.captured.len();
let mut in_axes = vec![None; ncap];
in_axes.extend(vec![Some(0); args.len()]);
let out_axes = vec![Some(0); traced.function.outvars.len()];
let body = ruxla_transforms::vmap_with_out_axes(&traced.function, &in_axes, &out_axes, n)
.unwrap_or_else(|e| panic!("vmap: {e}"));
let mut inputs = traced.captured;
inputs.extend(args);
let outs = trace::bind(
ruxla_prims::JIT,
&inputs,
Params::Jit {
name: String::from("vmap"),
body: Arc::new(body),
},
);
out.expect("the function was called")
.unflatten_like(&mut outs.into_iter())
}
pub fn make_ir<I, O>(&self, example: &I, n: usize) -> ruxla_ir::Function
where
I: Tree<Native>,
O: Tree<Trace>,
F: Fn(I::On<Trace>) -> O,
{
let (traced, _) = trace_with_output(&self.f, example);
let in_avals: Vec<AVal> = traced.function.in_avals();
let in_axes = vec![Some(0); in_avals.len()];
let out_axes = vec![Some(0); traced.function.outvars.len()];
ruxla_transforms::vmap_with_out_axes(&traced.function, &in_axes, &out_axes, n)
.unwrap_or_else(|e| panic!("vmap: {e}"))
}
}