1use std::any::Any;
4use std::collections::HashMap;
5use std::fmt;
6use std::sync::{Arc, Mutex, PoisonError};
7
8use ruxla_ir::{AVal, Function, HostArray, Params};
9use ruxla_pjrt::{Buffer, ExecuteOptions};
10
11use crate::backend::{Backend, Native, Trace};
12use crate::runtime::{self, Error, Platform};
13use crate::trace::{self, TraceRef, trace_function};
14use crate::transform::trace_with_output;
15use crate::tree::{Tree, TreeDef, leaves};
16
17pub fn jit<F>(f: F) -> Jit<F> {
39 Jit {
40 f,
41 name: String::from("jit"),
42 cache: Mutex::new(HashMap::new()),
43 skeletons: Mutex::new(HashMap::new()),
44 }
45}
46
47pub struct Jit<F> {
49 f: F,
50 name: String,
51 cache: Mutex<HashMap<(TreeDef, Vec<AVal>), Specialization>>,
52 skeletons: Mutex<HashMap<(TreeDef, Vec<AVal>), Specialization>>,
55}
56
57type Specialization = Arc<dyn Any + Send + Sync>;
60
61impl<F> fmt::Debug for Jit<F> {
62 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
63 f.debug_struct("Jit")
64 .field("name", &self.name)
65 .finish_non_exhaustive()
66 }
67}
68
69struct Compiled<O> {
71 function: Function,
72 out: O,
75 platform: Platform,
76}
77
78impl<F> Jit<F> {
79 pub fn with_name(mut self, name: impl Into<String>) -> Self {
81 self.name = name.into();
82 self
83 }
84
85 fn compiled<I, O>(&self, input: &I) -> Arc<Compiled<O>>
86 where
87 I: Tree<Native>,
88 O: Tree<Trace> + Send + Sync + 'static,
89 F: Fn(I::On<Trace>) -> O,
90 {
91 let avals: Vec<AVal> = leaves(input).iter().map(Native::leaf_aval).collect();
92 let key = (input.def(), avals);
93 let cached = self
94 .cache
95 .lock()
96 .unwrap_or_else(PoisonError::into_inner)
97 .get(&key)
98 .cloned();
99 if let Some(c) = cached.and_then(|c| c.downcast::<Compiled<O>>().ok()) {
100 return c;
101 }
102 let (traced, out) = trace_with_output(&self.f, input);
103 let compiled = Arc::new(Compiled {
104 function: traced.function,
105 out,
106 platform: runtime::platform(),
107 });
108 self.cache
109 .lock()
110 .unwrap_or_else(PoisonError::into_inner)
111 .insert(key, compiled.clone());
112 compiled
113 }
114
115 #[track_caller]
122 pub fn call<I, O>(&self, input: &I) -> O::On<Native>
123 where
124 I: Tree<Native>,
125 O: Tree<Trace> + Send + Sync + 'static,
126 F: Fn(I::On<Trace>) -> O,
127 {
128 self.try_call(input).unwrap_or_else(|e| panic!("{e}"))
129 }
130
131 pub fn try_call<I, O>(&self, input: &I) -> Result<O::On<Native>, Error>
138 where
139 I: Tree<Native>,
140 O: Tree<Trace> + Send + Sync + 'static,
141 F: Fn(I::On<Trace>) -> O,
142 {
143 let c = self.compiled::<I, O>(input);
144 let client = runtime::client(c.platform)?;
145 let buffers = leaves(input)
146 .iter()
147 .map(|a| client.buffer_from_host_array(a))
148 .collect::<Result<Vec<_>, _>>()?;
149 let outs = execute(&c, &buffers.iter().collect::<Vec<_>>())?;
150 let outs = outs
151 .iter()
152 .map(Buffer::to_host_array)
153 .collect::<Result<Vec<HostArray>, _>>()?;
154 Ok(c.out.rebuild::<Native>(&mut outs.into_iter()))
155 }
156
157 #[track_caller]
165 pub fn call_on_device<I, O>(&self, input: &OnDevice<I>) -> OnDevice<O::On<Native>>
166 where
167 I: Tree<Native>,
168 O: Tree<Trace> + Send + Sync + 'static,
169 O::On<Native>: Send + Sync + 'static,
170 F: Fn(I::On<Trace>) -> O,
171 {
172 let c = self.compiled::<I, O>(&input.skeleton);
173 assert_eq!(
174 c.platform, input.platform,
175 "the values are on another platform"
176 );
177 let args: Vec<&Buffer> = input.buffers.iter().map(Arc::as_ref).collect();
178 let exe = runtime::compile(c.platform, &c.function).unwrap_or_else(|e| panic!("{e}"));
179 let (outs, _done) = exe
182 .execute_with(&args, &ExecuteOptions::default())
183 .unwrap_or_else(|e| panic!("{e}"));
184 self.on_device(&c, &input.skeleton, outs)
185 }
186
187 #[track_caller]
198 pub fn call_on_device_donating<I, O>(&self, input: OnDevice<I>) -> OnDevice<O::On<Native>>
199 where
200 I: Tree<Native>,
201 O: Tree<Trace> + Send + Sync + 'static,
202 O::On<Native>: Send + Sync + 'static,
203 F: Fn(I::On<Trace>) -> O,
204 {
205 let c = self.compiled::<I, O>(&input.skeleton);
206 assert_eq!(
207 c.platform, input.platform,
208 "the values are on another platform"
209 );
210 let donated = vec![true; input.buffers.len()];
211 let exe = runtime::compile_donating(c.platform, &c.function, &donated)
212 .unwrap_or_else(|e| panic!("{e}"));
213 let options = ExecuteOptions {
214 non_donatable: input
215 .buffers
216 .iter()
217 .enumerate()
218 .filter(|(_, b)| Arc::strong_count(b) > 1)
219 .map(|(i, _)| i as i64)
220 .collect(),
221 };
222 let args: Vec<&Buffer> = input.buffers.iter().map(Arc::as_ref).collect();
223 let (outs, _done) = exe
224 .execute_with(&args, &options)
225 .unwrap_or_else(|e| panic!("{e}"));
226 self.on_device(&c, &input.skeleton, outs)
227 }
228
229 fn on_device<I, O>(
231 &self,
232 c: &Compiled<O>,
233 input: &I,
234 outs: Vec<Buffer>,
235 ) -> OnDevice<O::On<Native>>
236 where
237 I: Tree<Native>,
238 O: Tree<Trace> + Send + Sync + 'static,
239 O::On<Native>: Send + Sync + 'static,
240 {
241 let avals: Vec<AVal> = leaves(input).iter().map(Native::leaf_aval).collect();
242 let key = (input.def(), avals);
243 let cached = self
244 .skeletons
245 .lock()
246 .unwrap_or_else(PoisonError::into_inner)
247 .get(&key)
248 .cloned()
249 .and_then(|s| s.downcast::<O::On<Native>>().ok());
250 let skeleton = match cached {
251 Some(s) => (*s).clone(),
252 None => {
253 let zeros: Vec<HostArray> = c
256 .function
257 .out_avals()
258 .iter()
259 .map(|a| HostArray::zeros(a.shape.clone(), a.dtype))
260 .collect();
261 let s = c.out.rebuild::<Native>(&mut zeros.into_iter());
262 self.skeletons
263 .lock()
264 .unwrap_or_else(PoisonError::into_inner)
265 .insert(key, Arc::new(s.clone()));
266 s
267 }
268 };
269 OnDevice {
270 skeleton,
271 buffers: outs.into_iter().map(Arc::new).collect(),
272 platform: c.platform,
273 }
274 }
275
276 pub fn call_traced<I, O>(&self, input: I) -> O
279 where
280 I: Tree<Trace>,
281 O: Tree<Trace>,
282 F: Fn(I) -> O,
283 {
284 let args = leaves(&input);
285 let in_avals: Vec<AVal> = args.iter().map(|&r| trace::aval(r)).collect();
286 let mut out: Option<O> = None;
287 let traced = trace_function(&in_avals, |refs| {
288 let o = (self.f)(input.unflatten_like(&mut refs.iter().copied()));
289 let l = leaves(&o);
290 out = Some(o);
291 l
292 });
293 let mut inputs: Vec<TraceRef> = traced.captured;
294 inputs.extend(args);
295 let outs = trace::bind(
296 ruxla_prims::JIT,
297 &inputs,
298 Params::Jit {
299 name: self.name.clone(),
300 body: Arc::new(traced.function),
301 },
302 );
303 out.expect("the function was called")
304 .unflatten_like(&mut outs.into_iter())
305 }
306}
307
308fn execute<O>(c: &Compiled<O>, args: &[&Buffer]) -> Result<Vec<Buffer>, Error> {
309 let exe = runtime::compile(c.platform, &c.function)?;
310 Ok(exe.execute(args)?)
311}
312
313pub struct OnDevice<T> {
319 skeleton: T,
322 buffers: Vec<Arc<Buffer>>,
323 platform: Platform,
324}
325
326impl<T: Clone> Clone for OnDevice<T> {
327 fn clone(&self) -> Self {
328 Self {
329 skeleton: self.skeleton.clone(),
330 buffers: self.buffers.clone(),
331 platform: self.platform,
332 }
333 }
334}
335
336impl<T> fmt::Debug for OnDevice<T> {
337 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
338 f.debug_struct("OnDevice")
339 .field("platform", &self.platform)
340 .field("leaves", &self.buffers.len())
341 .finish_non_exhaustive()
342 }
343}
344
345impl<T: Tree<Native>> OnDevice<T> {
346 pub fn to_native(&self) -> T {
352 let host: Vec<HostArray> = self
353 .buffers
354 .iter()
355 .map(|b| b.to_host_array().unwrap_or_else(|e| panic!("{e}")))
356 .collect();
357 self.skeleton.unflatten_like(&mut host.into_iter())
358 }
359}
360
361pub fn device_put<T: Tree<Native>>(x: &T) -> OnDevice<T> {
368 let platform = runtime::platform();
369 let client = runtime::client(platform).unwrap_or_else(|e| panic!("{e}"));
370 let buffers = leaves(x)
371 .iter()
372 .map(|a| {
373 client
374 .buffer_from_host_array(a)
375 .map(Arc::new)
376 .unwrap_or_else(|e| panic!("{e}"))
377 })
378 .collect();
379 OnDevice {
380 skeleton: x.clone(),
381 buffers,
382 platform,
383 }
384}