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