Skip to main content

yscv_tensor/
aligned.rs

1//! A Vec-like container guaranteeing cacheline-aligned allocation for SIMD operations.
2
3use std::fmt;
4use std::iter::FromIterator;
5use std::ops::{Deref, DerefMut};
6
7/// Default alignment in bytes for AlignedVec allocations.
8///
9/// **64 bytes = one Zen 4 / Intel cacheline.** Avoids cacheline-split loads
10/// at the start of any allocation. Strict superset of AVX-512 (64B), AVX/AVX2
11/// (32B), and NEON (16B) alignment requirements.
12const ALIGN: usize = 64;
13
14/// Types for which every-zero bytes form a valid value.
15///
16/// Implementors must guarantee that `0u8` repeated over `size_of::<Self>()`
17/// bytes is a valid initialized value. This is exactly the precondition needed
18/// by [`AlignedVec::calloc`].
19///
20/// # Safety
21/// Implementing this trait for a type whose all-zero byte pattern is invalid
22/// permits undefined behavior when `calloc` constructs that type.
23pub unsafe trait Zeroable: Copy {}
24
25macro_rules! impl_zeroable {
26    ($($ty:ty),+ $(,)?) => {
27        $(
28            // SAFETY: all-zero is a valid representation for primitive numeric types.
29            unsafe impl Zeroable for $ty {}
30        )+
31    };
32}
33
34impl_zeroable!(
35    u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize, f32, f64
36);
37
38/// Pick the alignment for a given byte size. Returns the cacheline constant
39/// unconditionally (size-tiered page-alignment for large allocations was
40/// tried and regressed). The size parameter stays in the API for forward
41/// compatibility.
42#[inline]
43const fn align_for_size(_size: usize) -> usize {
44    ALIGN
45}
46
47/// A Vec-like container that guarantees 64-byte (cacheline) alignment for the
48/// data pointer.
49///
50/// 64 bytes is one cacheline on Zen 4 / modern Intel; aligned to this avoids
51/// any cacheline-split load at the first element. Strict superset of AVX-512
52/// (64B), AVX/AVX2 (32B), and NEON (16B) requirements. Standard `Vec<f32>`
53/// only guarantees 4-byte alignment.
54pub struct AlignedVec<T> {
55    ptr: *mut T,
56    len: usize,
57    cap: usize,
58}
59
60// SAFETY: AlignedVec owns its data exclusively, so it is safe to Send/Sync
61// when T is Send/Sync (same guarantees as Vec<T>).
62#[allow(unsafe_code)]
63unsafe impl<T: Send> Send for AlignedVec<T> {}
64#[allow(unsafe_code)]
65unsafe impl<T: Sync> Sync for AlignedVec<T> {}
66
67impl<T> Default for AlignedVec<T> {
68    fn default() -> Self {
69        Self::new()
70    }
71}
72
73impl<T> AlignedVec<T> {
74    /// Creates a new empty `AlignedVec` with no allocation.
75    #[inline]
76    pub const fn new() -> Self {
77        Self {
78            ptr: std::ptr::NonNull::dangling().as_ptr(),
79            len: 0,
80            cap: 0,
81        }
82    }
83
84    /// Creates an `AlignedVec` with the given capacity (aligned to 32 bytes).
85    #[allow(unsafe_code)]
86    pub fn with_capacity(cap: usize) -> Self {
87        if cap == 0 {
88            return Self::new();
89        }
90        let ptr = alloc_aligned::<T>(cap);
91        Self { ptr, len: 0, cap }
92    }
93
94    /// Creates an `AlignedVec` from an existing `Vec<T>`, copying data into
95    /// aligned storage. Requires `T: Copy` to ensure bitwise copy is sound.
96    #[allow(unsafe_code)]
97    pub fn from_vec(v: Vec<T>) -> Self
98    where
99        T: Copy,
100    {
101        let len = v.len();
102        if len == 0 {
103            return Self::new();
104        }
105        let ptr = alloc_aligned::<T>(len);
106        // SAFETY: ptr is valid for len elements, v.as_ptr() is valid for len elements,
107        // they do not overlap (fresh allocation).
108        unsafe {
109            std::ptr::copy_nonoverlapping(v.as_ptr(), ptr, len);
110        }
111        // v is dropped here normally — T: Copy so no element destructors,
112        // and Vec's drop frees the backing allocation.
113        drop(v);
114        Self { ptr, len, cap: len }
115    }
116
117    /// Returns the number of elements.
118    #[inline]
119    pub const fn len(&self) -> usize {
120        self.len
121    }
122
123    /// Returns `true` if the vec is empty.
124    #[inline]
125    pub const fn is_empty(&self) -> bool {
126        self.len == 0
127    }
128
129    /// Returns a raw pointer to the aligned data.
130    #[inline]
131    pub const fn as_ptr(&self) -> *const T {
132        self.ptr
133    }
134
135    /// Returns a mutable raw pointer to the aligned data.
136    #[inline]
137    pub const fn as_mut_ptr(&mut self) -> *mut T {
138        self.ptr
139    }
140
141    /// Returns an immutable slice over the contained elements.
142    #[inline]
143    #[allow(unsafe_code)]
144    pub const fn as_slice(&self) -> &[T] {
145        if self.len == 0 {
146            return &[];
147        }
148        // SAFETY: ptr is valid for self.len elements, properly aligned.
149        unsafe { std::slice::from_raw_parts(self.ptr, self.len) }
150    }
151
152    /// Returns a mutable slice over the contained elements.
153    #[inline]
154    #[allow(unsafe_code)]
155    pub const fn as_mut_slice(&mut self) -> &mut [T] {
156        if self.len == 0 {
157            return &mut [];
158        }
159        // SAFETY: ptr is valid for self.len elements, properly aligned, uniquely borrowed.
160        unsafe { std::slice::from_raw_parts_mut(self.ptr, self.len) }
161    }
162
163    /// Appends a value to the end, growing if necessary.
164    #[allow(unsafe_code)]
165    pub fn push(&mut self, val: T) {
166        if self.len == self.cap {
167            self.grow();
168        }
169        // SAFETY: after grow, self.cap > self.len, so ptr.add(self.len) is valid.
170        unsafe {
171            self.ptr.add(self.len).write(val);
172        }
173        self.len += 1;
174    }
175
176    /// Grows the backing allocation (doubles capacity, minimum 4).
177    #[allow(unsafe_code)]
178    fn grow(&mut self) {
179        let new_cap = if self.cap == 0 {
180            4
181        } else {
182            self.cap.checked_mul(2).expect("capacity overflow")
183        };
184        let new_ptr = alloc_aligned::<T>(new_cap);
185        if self.cap > 0 {
186            if self.len > 0 {
187                // SAFETY: old ptr valid for self.len elements, new ptr valid for new_cap >= self.len.
188                unsafe {
189                    std::ptr::copy_nonoverlapping(self.ptr, new_ptr, self.len);
190                }
191            }
192            dealloc_aligned::<T>(self.ptr, self.cap);
193        }
194        self.ptr = new_ptr;
195        self.cap = new_cap;
196    }
197}
198
199impl<T: Copy> AlignedVec<T> {
200    /// Creates an `AlignedVec` with `len` elements of **uninitialized** memory.
201    ///
202    /// The caller **must** write every element before reading any of them.
203    /// This avoids the cost of zeroing the buffer when a subsequent SIMD pass
204    /// will overwrite every element anyway.
205    ///
206    /// # Safety
207    /// The allocation is valid and aligned, but the contents are indeterminate.
208    /// The caller must initialize every element before any read or drop of the
209    /// returned vector. Reading an uninitialized element is undefined behaviour.
210    #[allow(unsafe_code)]
211    #[inline]
212    pub unsafe fn uninitialized(len: usize) -> Self {
213        if len == 0 {
214            return Self::new();
215        }
216        let ptr = alloc_aligned::<T>(len);
217        Self { ptr, len, cap: len }
218    }
219}
220
221impl<T: Default + Copy> AlignedVec<T> {
222    /// Creates an `AlignedVec` of `len` elements, each set to `val`.
223    #[allow(unsafe_code)]
224    pub fn filled(len: usize, val: T) -> Self {
225        if len == 0 {
226            return Self::new();
227        }
228        let ptr = alloc_aligned::<T>(len);
229        // SAFETY: ptr is valid for len elements.
230        unsafe {
231            for i in 0..len {
232                ptr.add(i).write(val);
233            }
234        }
235        Self { ptr, len, cap: len }
236    }
237
238    /// Creates an `AlignedVec` of `len` zero/default elements.
239    pub fn zeros(len: usize) -> Self {
240        Self::filled(len, T::default())
241    }
242}
243
244impl<T: Zeroable> AlignedVec<T> {
245    /// Creates an `AlignedVec` of `len` elements using an all-zero allocation.
246    ///
247    /// The [`Zeroable`] bound makes the representation guarantee explicit at
248    /// the API boundary; arbitrary generic `T` can no longer be passed here.
249    #[allow(unsafe_code)]
250    pub fn calloc(len: usize) -> Self {
251        if len == 0 {
252            return Self::new();
253        }
254        let size = len
255            .checked_mul(std::mem::size_of::<T>())
256            .expect("allocation size overflow");
257        let size = size.max(1);
258        let align = align_for_size(size);
259        let layout =
260            std::alloc::Layout::from_size_align(size, align).expect("invalid allocation layout");
261        // SAFETY: layout has non-zero size. alloc_zeroed returns zeroed memory.
262        let ptr = unsafe { std::alloc::alloc_zeroed(layout) };
263        if ptr.is_null() {
264            std::alloc::handle_alloc_error(layout);
265        }
266        Self {
267            ptr: ptr as *mut T,
268            len,
269            cap: len,
270        }
271    }
272}
273
274impl<T> Drop for AlignedVec<T> {
275    #[allow(unsafe_code)]
276    fn drop(&mut self) {
277        if self.cap == 0 {
278            return;
279        }
280        // Drop elements in place.
281        unsafe {
282            std::ptr::drop_in_place(std::ptr::slice_from_raw_parts_mut(self.ptr, self.len));
283        }
284        dealloc_aligned::<T>(self.ptr, self.cap);
285    }
286}
287
288impl<T: Clone> Clone for AlignedVec<T> {
289    #[allow(unsafe_code)]
290    fn clone(&self) -> Self {
291        if self.len == 0 {
292            return Self::new();
293        }
294        let ptr = alloc_aligned::<T>(self.len);
295        // SAFETY: ptr valid for self.len elements, we write each one via clone.
296        unsafe {
297            for i in 0..self.len {
298                ptr.add(i).write((*self.ptr.add(i)).clone());
299            }
300        }
301        Self {
302            ptr,
303            len: self.len,
304            cap: self.len,
305        }
306    }
307}
308
309impl<T: fmt::Debug> fmt::Debug for AlignedVec<T> {
310    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
311        f.debug_list().entries(self.as_slice().iter()).finish()
312    }
313}
314
315impl<T: PartialEq> PartialEq for AlignedVec<T> {
316    fn eq(&self, other: &Self) -> bool {
317        self.as_slice() == other.as_slice()
318    }
319}
320
321impl<T> Deref for AlignedVec<T> {
322    type Target = [T];
323
324    #[inline]
325    fn deref(&self) -> &[T] {
326        self.as_slice()
327    }
328}
329
330impl<T> DerefMut for AlignedVec<T> {
331    #[inline]
332    fn deref_mut(&mut self) -> &mut [T] {
333        self.as_mut_slice()
334    }
335}
336
337impl<T> FromIterator<T> for AlignedVec<T> {
338    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
339        let iter = iter.into_iter();
340        let (lower, _) = iter.size_hint();
341        let mut v = AlignedVec::with_capacity(lower);
342        for item in iter {
343            v.push(item);
344        }
345        v
346    }
347}
348
349// ── Allocation helpers ─────────────────────────────────────────────
350
351/// Allocates aligned memory for `count` elements of type `T`.
352/// Thread-local cache of freed aligned allocations.
353/// Avoids repeated mmap/munmap for same-size buffers (like PyTorch's CachingAllocator).
354/// Each entry: `(pointer, byte_size, alignment)`. The alignment is part of the
355/// key so the cache never hands a 64B-aligned pointer back for a request that
356/// needs a larger alignment — that would be undefined behaviour.
357#[allow(unsafe_code)]
358mod alloc_cache {
359
360    use std::cell::RefCell;
361
362    const MAX_CACHED: usize = 16;
363
364    struct AllocCache {
365        entries: Vec<(*mut u8, usize, usize)>,
366    }
367
368    impl AllocCache {
369        const fn new() -> Self {
370            Self {
371                entries: Vec::new(),
372            }
373        }
374    }
375
376    impl Drop for AllocCache {
377        fn drop(&mut self) {
378            for &(ptr, size, align) in &self.entries {
379                if !ptr.is_null()
380                    && let Ok(layout) = std::alloc::Layout::from_size_align(size, align)
381                {
382                    unsafe {
383                        std::alloc::dealloc(ptr, layout);
384                    }
385                }
386            }
387        }
388    }
389
390    thread_local! {
391        static CACHE: RefCell<AllocCache> = const { RefCell::new(AllocCache::new()) };
392    }
393
394    pub(super) fn try_alloc(size: usize, align: usize) -> Option<*mut u8> {
395        if cfg!(miri) {
396            return None;
397        }
398        CACHE
399            .try_with(|c| {
400                let mut cache = c.borrow_mut();
401                // Check last entry first (MRU — temporal locality for inference loops)
402                if let Some(&(_, s, a)) = cache.entries.last()
403                    && s == size
404                    && a == align
405                {
406                    let (ptr, _, _) = cache.entries.pop().unwrap();
407                    return Some(ptr);
408                }
409                // Fallback: linear scan
410                if let Some(pos) = cache
411                    .entries
412                    .iter()
413                    .position(|&(_, s, a)| s == size && a == align)
414                {
415                    let (ptr, _, _) = cache.entries.swap_remove(pos);
416                    Some(ptr)
417                } else {
418                    None
419                }
420            })
421            .ok()
422            .flatten()
423    }
424
425    pub(super) fn try_dealloc(ptr: *mut u8, size: usize, align: usize) -> bool {
426        if cfg!(miri) {
427            return false;
428        }
429        CACHE
430            .try_with(|c| {
431                let mut cache = c.borrow_mut();
432                if cache.entries.len() < MAX_CACHED {
433                    cache.entries.push((ptr, size, align));
434                    true
435                } else {
436                    false
437                }
438            })
439            .unwrap_or(false)
440    }
441}
442
443#[allow(unsafe_code)]
444fn alloc_aligned<T>(count: usize) -> *mut T {
445    assert!(count > 0, "cannot allocate zero-sized aligned buffer");
446    let size = count
447        .checked_mul(std::mem::size_of::<T>())
448        .expect("allocation size overflow");
449    let size = size.max(1);
450    let align = align_for_size(size);
451
452    // Try thread-local cache first — cache is keyed by (size, align) so we
453    // only return a pointer that matches BOTH the requested size and align.
454    if let Some(ptr) = alloc_cache::try_alloc(size, align) {
455        return ptr as *mut T;
456    }
457
458    let layout =
459        std::alloc::Layout::from_size_align(size, align).expect("invalid allocation layout");
460    // SAFETY: layout has non-zero size.
461    let ptr = unsafe { std::alloc::alloc(layout) };
462    if ptr.is_null() {
463        std::alloc::handle_alloc_error(layout);
464    }
465    ptr as *mut T
466}
467
468/// Deallocates aligned memory previously allocated with `alloc_aligned`.
469#[allow(unsafe_code)]
470fn dealloc_aligned<T>(ptr: *mut T, cap: usize) {
471    let size = match cap.checked_mul(std::mem::size_of::<T>()) {
472        Some(s) => s.max(1),
473        None => return, // overflow — cannot reconstruct layout, leak rather than panic in Drop
474    };
475    let align = align_for_size(size);
476
477    // Try to cache instead of freeing
478    if alloc_cache::try_dealloc(ptr as *mut u8, size, align) {
479        return;
480    }
481
482    if let Ok(layout) = std::alloc::Layout::from_size_align(size, align) {
483        // SAFETY: ptr was allocated with this layout via alloc_aligned.
484        unsafe {
485            std::alloc::dealloc(ptr as *mut u8, layout);
486        }
487    }
488}
489
490#[cfg(test)]
491mod tests {
492    use super::*;
493
494    #[test]
495    fn alignment_is_32_bytes() {
496        let v = AlignedVec::<f32>::with_capacity(64);
497        assert_eq!(v.as_ptr() as usize % 32, 0);
498    }
499
500    #[test]
501    fn filled_and_len() {
502        let v = AlignedVec::filled(100, 1.0f32);
503        assert_eq!(v.len(), 100);
504        assert!(v.iter().all(|&x| x == 1.0));
505        assert_eq!(v.as_ptr() as usize % 32, 0);
506    }
507
508    #[test]
509    fn zeros_default() {
510        let v = AlignedVec::<f32>::zeros(16);
511        assert_eq!(v.len(), 16);
512        assert!(v.iter().all(|&x| x == 0.0));
513    }
514
515    #[test]
516    fn from_vec_copies_and_aligns() {
517        let orig = vec![1.0f32, 2.0, 3.0, 4.0];
518        let aligned = AlignedVec::from_vec(orig);
519        assert_eq!(aligned.as_slice(), &[1.0, 2.0, 3.0, 4.0]);
520        assert_eq!(aligned.as_ptr() as usize % 32, 0);
521    }
522
523    #[test]
524    fn push_and_grow() {
525        let mut v = AlignedVec::<f32>::new();
526        for i in 0..100 {
527            v.push(i as f32);
528        }
529        assert_eq!(v.len(), 100);
530        assert_eq!(v[50], 50.0);
531        assert_eq!(v.as_ptr() as usize % 32, 0);
532    }
533
534    #[test]
535    fn clone_preserves_alignment() {
536        let v = AlignedVec::filled(10, 42.0f32);
537        let v2 = v.clone();
538        assert_eq!(v.as_slice(), v2.as_slice());
539        assert_eq!(v2.as_ptr() as usize % 32, 0);
540    }
541
542    #[test]
543    fn from_iterator() {
544        let v: AlignedVec<f32> = (0..10).map(|i| i as f32).collect();
545        assert_eq!(v.len(), 10);
546        assert_eq!(v[5], 5.0);
547        assert_eq!(v.as_ptr() as usize % 32, 0);
548    }
549
550    #[test]
551    fn empty_vec_operations() {
552        let v = AlignedVec::<f32>::new();
553        assert!(v.is_empty());
554        assert_eq!(v.len(), 0);
555        assert_eq!(v.as_slice(), &[] as &[f32]);
556    }
557
558    #[test]
559    fn deref_slice_access() {
560        let v = AlignedVec::filled(5, 3.0f32);
561        // Test that Deref to [T] works
562        let sum: f32 = v.iter().sum();
563        assert_eq!(sum, 15.0);
564    }
565}