Skip to main content

ruxla_codegen/
rt.rs

1//! Helpers that generated code calls (not meant to be used directly).
2
3use 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/// `[f(0), f(1), ..., f(N - 1)]`.
14#[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
23/// A cumulative reduction of `x` (of shape `shape`) along `axis`, in the
24/// order XLA combines the elements on CPU (`ruxla_kernels::array::cumulative`).
25///
26/// # Panics
27///
28/// Panics if `x` does not have `N` elements or `shape` does not fit it.
29pub 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/// `conv_general_dilated` of operands of the result's type
42/// (`ruxla_kernels::window::conv_general_dilated`).
43///
44/// # Panics
45///
46/// Panics if the result does not have `N` elements.
47#[allow(clippy::too_many_arguments)] // The parameters of the primitive.
48pub 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
72/// An array of `N` elements on the heap whose buffer goes back to a pool of
73/// the thread when dropped, for the next array of the same layout: the
74/// large arrays of a step are allocated again at every step, and fresh
75/// allocations of that size are mapped pages that fault and are zeroed by
76/// the system at every first touch.
77pub struct Heap<T: Copy + 'static, const N: usize> {
78    ptr: std::ptr::NonNull<[T; N]>,
79}
80
81// SAFETY: `Heap` owns its buffer exclusively (like `Box<[T; N]>`), so it is
82// `Send` and `Sync` exactly when `T` is.
83unsafe impl<T: Copy + Send + 'static, const N: usize> Send for Heap<T, N> {}
84// SAFETY: as above; shared references give only shared access.
85unsafe impl<T: Copy + Sync + 'static, const N: usize> Sync for Heap<T, N> {}
86
87thread_local! {
88    /// The free buffers of the thread, by element type and number: each
89    /// holds the values of a former array of that type, so a buffer taken
90    /// from the pool is initialized.
91    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
95/// The most free buffers kept for one layout.
96const 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    /// A buffer of the pool (holding the values of a former array of `N`
108    /// elements of `T`).
109    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            // SAFETY: the pool holds only buffers allocated (not null) with
113            // this layout for arrays of `N` elements of `T`, which stay
114            // initialized.
115            ptr: unsafe { std::ptr::NonNull::new_unchecked(addr as *mut [T; N]) },
116        })
117    }
118
119    /// An array whose elements the caller overwrites before reading them:
120    /// a buffer of the pool as it is (the values of a former array), or a
121    /// new array of `N` copies of `x`.
122    pub fn reused(x: T) -> Self {
123        Self::take().unwrap_or_else(|| Self::filled(x))
124    }
125
126    /// An array of `N` copies of `x`.
127    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        // SAFETY: the layout has a nonzero size (checked above).
135        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            // SAFETY: the buffer holds `N` elements of `T` (its layout is
142            // that of `[T; N]`); writing initializes each element.
143            unsafe { elems.add(i).write(x) };
144        }
145        Heap {
146            // SAFETY: `raw` is not null (checked above).
147            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            // SAFETY: the buffer was allocated with this layout and is not
170            // used after the drop.
171            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        // SAFETY: the buffer is initialized (by `filled`) and owned by `self`.
180        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        // SAFETY: as above, and `&mut self` gives exclusive access.
187        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
197/// An array of `N` copies of `x` on the heap (without a copy on the stack).
198pub fn filled<T: Copy + 'static, const N: usize>(x: T) -> Heap<T, N> {
199    Heap::filled(x)
200}
201
202/// An array of `N` elements on the heap that the caller overwrites before
203/// reading ([`Heap::reused`]).
204pub fn reused<T: Copy + 'static, const N: usize>(x: T) -> Heap<T, N> {
205    Heap::reused(x)
206}
207
208/// An array (on the stack) that the caller overwrites before reading; the
209/// generated code writes it so for [`reused`] on the heap.
210#[inline(always)]
211pub fn overwritten<T: Copy, const N: usize>(x: [T; N]) -> [T; N] {
212    x
213}
214
215/// [`build`] on the heap.
216#[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
227/// A copy of `x` on the heap.
228pub 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
234/// `top_k` along `axis` (`ruxla_kernels::array::top_k`): the values and their
235/// indices.
236///
237/// # Panics
238///
239/// Panics if the results do not have `N` elements.
240pub 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
257/// The Cholesky factors (lower) of `batch` matrices `n x n`
258/// (`ruxla_kernels::linalg::cholesky`: NaN where a matrix is not positive
259/// definite).
260///
261/// # Panics
262///
263/// Panics if `a` or the result does not have `N` elements.
264pub 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
274/// `triangular_solve` of `batch` systems with right-hand sides `m x n`
275/// (`ruxla_kernels::linalg::triangular_solve`; the flags as its options:
276/// left side, lower, transpose, conjugate, unit diagonal).
277///
278/// # Panics
279///
280/// Panics if the operands or the result do not have those sizes.
281pub 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
299/// A host array of `data` with shape `dims`.
300pub fn host<T: Element>(data: &[T], dims: &[usize]) -> HostArray {
301    HostArray::from_vec(data.to_vec(), dims)
302}
303
304/// The elements of a host array of `N` elements of type `T`.
305///
306/// # Panics
307///
308/// Panics if the array does not have `N` elements of type `T`.
309pub 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
314/// The element of a host array of one element of type `T`.
315///
316/// # Panics
317///
318/// Panics if the array does not have one element of type `T`.
319pub fn from_host_scalar<T: Element>(h: &HostArray) -> T {
320    h.as_slice::<T>().expect("the element type of the result")[0]
321}
322
323/// Evaluates a serialized function (deserialized once into `cell`) with
324/// the interpreter: the equations that generated code does not specialize.
325///
326/// # Panics
327///
328/// Panics if `bytes` is not a function of ruxla's primitives or the
329/// evaluation fails (the inputs are those that the function was generated
330/// for).
331pub 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}