1use std::sync::OnceLock;
4
5pub use ruxla_ir::{Function, HostArray};
6pub use ruxla_kernels::array::{CumulativeOp, sort_order};
7pub use ruxla_kernels::random::threefry2x32;
8pub use ruxla_kernels::window::{ConvDims, ConvWindow};
9pub use ruxla_kernels::{
10 BinaryOp, CompareOp, Element, Ops, UnaryOp, bf16, cast, compare, f16, integer_pow,
11};
12
13#[inline(always)]
15pub fn build<T: Copy + Default, const N: usize>(mut f: impl FnMut(usize) -> T) -> [T; N] {
16 let mut out = [T::default(); N];
17 for (i, o) in out.iter_mut().enumerate() {
18 *o = f(i);
19 }
20 out
21}
22
23pub fn cumulative<T: Element, const N: usize>(
30 x: &[T],
31 shape: &[usize],
32 axis: usize,
33 reverse: bool,
34 op: CumulativeOp,
35) -> [T; N] {
36 let mut out = [T::default(); N];
37 ruxla_kernels::array::cumulative_into(x, shape, axis, reverse, op, &mut out);
38 out
39}
40
41#[allow(clippy::too_many_arguments)] pub fn conv<T: Element, const N: usize>(
49 lhs: &[T],
50 lshape: &[usize],
51 rhs: &[T],
52 rshape: &[usize],
53 window: &ConvWindow<'_>,
54 dims: &ConvDims,
55 feature_group_count: usize,
56 batch_group_count: usize,
57) -> [T; N] {
58 ruxla_kernels::window::conv_general_dilated(
59 lhs,
60 lshape,
61 rhs,
62 rshape,
63 window,
64 dims,
65 feature_group_count,
66 batch_group_count,
67 )
68 .try_into()
69 .unwrap_or_else(|_| panic!("a convolution of {N} elements"))
70}
71
72pub struct Heap<T: Copy + 'static, const N: usize> {
78 ptr: std::ptr::NonNull<[T; N]>,
79}
80
81unsafe impl<T: Copy + Send + 'static, const N: usize> Send for Heap<T, N> {}
84unsafe impl<T: Copy + Sync + 'static, const N: usize> Sync for Heap<T, N> {}
86
87thread_local! {
88 static POOL: std::cell::RefCell<std::collections::HashMap<(std::any::TypeId, usize), Vec<usize>>> =
92 std::cell::RefCell::new(std::collections::HashMap::new());
93}
94
95const POOL_PER_LAYOUT: usize = 64;
97
98impl<T: Copy + 'static, const N: usize> Heap<T, N> {
99 fn layout() -> std::alloc::Layout {
100 std::alloc::Layout::new::<[T; N]>()
101 }
102
103 fn key() -> (std::any::TypeId, usize) {
104 (std::any::TypeId::of::<T>(), N)
105 }
106
107 fn take() -> Option<Self> {
110 let addr = POOL.with(|p| p.borrow_mut().get_mut(&Self::key()).and_then(Vec::pop))?;
111 Some(Heap {
112 ptr: unsafe { std::ptr::NonNull::new_unchecked(addr as *mut [T; N]) },
116 })
117 }
118
119 pub fn reused(x: T) -> Self {
123 Self::take().unwrap_or_else(|| Self::filled(x))
124 }
125
126 pub fn filled(x: T) -> Self {
128 let layout = Self::layout();
129 assert!(layout.size() > 0, "a heap array of no bytes");
130 if let Some(mut h) = Self::take() {
131 h.fill(x);
132 return h;
133 }
134 let raw = unsafe { std::alloc::alloc(layout) } as *mut [T; N];
136 if raw.is_null() {
137 std::alloc::handle_alloc_error(layout);
138 }
139 let elems = raw as *mut T;
140 for i in 0..N {
141 unsafe { elems.add(i).write(x) };
144 }
145 Heap {
146 ptr: unsafe { std::ptr::NonNull::new_unchecked(raw) },
148 }
149 }
150}
151
152impl<T: Copy + 'static, const N: usize> Drop for Heap<T, N> {
153 fn drop(&mut self) {
154 let layout = Self::layout();
155 let addr = self.ptr.as_ptr() as usize;
156 let kept = POOL
157 .try_with(|p| {
158 let mut p = p.borrow_mut();
159 let free = p.entry(Self::key()).or_default();
160 if free.len() < POOL_PER_LAYOUT {
161 free.push(addr);
162 true
163 } else {
164 false
165 }
166 })
167 .unwrap_or(false);
168 if !kept {
169 unsafe { std::alloc::dealloc(self.ptr.as_ptr() as *mut u8, layout) };
172 }
173 }
174}
175
176impl<T: Copy + 'static, const N: usize> std::ops::Deref for Heap<T, N> {
177 type Target = [T; N];
178 fn deref(&self) -> &[T; N] {
179 unsafe { self.ptr.as_ref() }
181 }
182}
183
184impl<T: Copy + 'static, const N: usize> std::ops::DerefMut for Heap<T, N> {
185 fn deref_mut(&mut self) -> &mut [T; N] {
186 unsafe { self.ptr.as_mut() }
188 }
189}
190
191impl<T: Copy + std::fmt::Debug + 'static, const N: usize> std::fmt::Debug for Heap<T, N> {
192 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
193 f.debug_list().entries(self.iter()).finish()
194 }
195}
196
197pub fn filled<T: Copy + 'static, const N: usize>(x: T) -> Heap<T, N> {
199 Heap::filled(x)
200}
201
202pub fn reused<T: Copy + 'static, const N: usize>(x: T) -> Heap<T, N> {
205 Heap::reused(x)
206}
207
208#[inline(always)]
211pub fn overwritten<T: Copy, const N: usize>(x: [T; N]) -> [T; N] {
212 x
213}
214
215#[inline(always)]
217pub fn build_boxed<T: Copy + Default + 'static, const N: usize>(
218 mut f: impl FnMut(usize) -> T,
219) -> Heap<T, N> {
220 let mut out = Heap::<T, N>::reused(T::default());
221 for (i, o) in out.iter_mut().enumerate() {
222 *o = f(i);
223 }
224 out
225}
226
227pub fn boxed_copy<T: Copy + Default + 'static, const N: usize>(x: &[T; N]) -> Heap<T, N> {
229 let mut out = Heap::<T, N>::reused(T::default());
230 out.copy_from_slice(x);
231 out
232}
233
234pub fn top_k<T: Element, const N: usize>(
241 x: &[T],
242 shape: &[usize],
243 k: usize,
244 axis: usize,
245) -> ([T; N], [i32; N]) {
246 let (values, indices) = ruxla_kernels::array::top_k(x, shape, k, axis);
247 (
248 values
249 .try_into()
250 .unwrap_or_else(|_| panic!("top_k of {N} elements")),
251 indices
252 .try_into()
253 .unwrap_or_else(|_| panic!("top_k of {N} elements")),
254 )
255}
256
257pub fn cholesky<T: ruxla_kernels::linalg::LinalgScalar, const N: usize>(
265 a: &[T],
266 batch: usize,
267 n: usize,
268) -> [T; N] {
269 ruxla_kernels::linalg::cholesky(a, batch, n)
270 .try_into()
271 .unwrap_or_else(|_| panic!("cholesky of {N} elements"))
272}
273
274pub fn triangular_solve<T: ruxla_kernels::linalg::LinalgScalar, const N: usize>(
282 a: &[T],
283 b: &[T],
284 (batch, m, n): (usize, usize, usize),
285 [left_side, lower, transpose_a, conjugate_a, unit_diagonal]: [bool; 5],
286) -> [T; N] {
287 let options = ruxla_kernels::linalg::TriangularSolveOptions {
288 left_side,
289 lower,
290 transpose_a,
291 conjugate_a,
292 unit_diagonal,
293 };
294 ruxla_kernels::linalg::triangular_solve(a, b, batch, m, n, options)
295 .try_into()
296 .unwrap_or_else(|_| panic!("triangular_solve of {N} elements"))
297}
298
299pub fn host<T: Element>(data: &[T], dims: &[usize]) -> HostArray {
301 HostArray::from_vec(data.to_vec(), dims)
302}
303
304pub fn from_host<T: Element, const N: usize>(h: &HostArray) -> [T; N] {
310 let v = h.as_slice::<T>().expect("the element type of the result");
311 v.try_into().expect("the size of the result")
312}
313
314pub fn from_host_scalar<T: Element>(h: &HostArray) -> T {
320 h.as_slice::<T>().expect("the element type of the result")[0]
321}
322
323pub fn eval(cell: &OnceLock<Function>, bytes: &[u8], inputs: Vec<HostArray>) -> Vec<HostArray> {
332 let f = cell.get_or_init(|| {
333 ruxla_ir::serialize::from_bytes(bytes, &ruxla_prims::by_name)
334 .expect("a function serialized by ruxla-codegen")
335 });
336 ruxla_interp::eval(f, &inputs).expect("the evaluation of a generated fallback")
337}