yscv-tensor 0.2.0

SIMD-accelerated tensor library with f32/f16/bf16 support and 80+ operations
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
//! A Vec-like container guaranteeing cacheline-aligned allocation for SIMD operations.

use std::fmt;
use std::iter::FromIterator;
use std::ops::{Deref, DerefMut};

/// Default alignment in bytes for AlignedVec allocations.
///
/// **64 bytes = one Zen 4 / Intel cacheline.** Avoids cacheline-split loads
/// at the start of any allocation. Strict superset of AVX-512 (64B), AVX/AVX2
/// (32B), and NEON (16B) alignment requirements.
const ALIGN: usize = 64;

/// Types for which every-zero bytes form a valid value.
///
/// Implementors must guarantee that `0u8` repeated over `size_of::<Self>()`
/// bytes is a valid initialized value. This is exactly the precondition needed
/// by [`AlignedVec::calloc`].
///
/// # Safety
/// Implementing this trait for a type whose all-zero byte pattern is invalid
/// permits undefined behavior when `calloc` constructs that type.
pub unsafe trait Zeroable: Copy {}

macro_rules! impl_zeroable {
    ($($ty:ty),+ $(,)?) => {
        $(
            // SAFETY: all-zero is a valid representation for primitive numeric types.
            unsafe impl Zeroable for $ty {}
        )+
    };
}

impl_zeroable!(
    u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize, f32, f64
);

/// Pick the alignment for a given byte size. Returns the cacheline constant
/// unconditionally (size-tiered page-alignment for large allocations was
/// tried and regressed). The size parameter stays in the API for forward
/// compatibility.
#[inline]
const fn align_for_size(_size: usize) -> usize {
    ALIGN
}

/// A Vec-like container that guarantees 64-byte (cacheline) alignment for the
/// data pointer.
///
/// 64 bytes is one cacheline on Zen 4 / modern Intel; aligned to this avoids
/// any cacheline-split load at the first element. Strict superset of AVX-512
/// (64B), AVX/AVX2 (32B), and NEON (16B) requirements. Standard `Vec<f32>`
/// only guarantees 4-byte alignment.
pub struct AlignedVec<T> {
    ptr: *mut T,
    len: usize,
    cap: usize,
}

// SAFETY: AlignedVec owns its data exclusively, so it is safe to Send/Sync
// when T is Send/Sync (same guarantees as Vec<T>).
#[allow(unsafe_code)]
unsafe impl<T: Send> Send for AlignedVec<T> {}
#[allow(unsafe_code)]
unsafe impl<T: Sync> Sync for AlignedVec<T> {}

impl<T> Default for AlignedVec<T> {
    fn default() -> Self {
        Self::new()
    }
}

impl<T> AlignedVec<T> {
    /// Creates a new empty `AlignedVec` with no allocation.
    #[inline]
    pub const fn new() -> Self {
        Self {
            ptr: std::ptr::NonNull::dangling().as_ptr(),
            len: 0,
            cap: 0,
        }
    }

    /// Creates an `AlignedVec` with the given capacity (aligned to 32 bytes).
    #[allow(unsafe_code)]
    pub fn with_capacity(cap: usize) -> Self {
        if cap == 0 {
            return Self::new();
        }
        let ptr = alloc_aligned::<T>(cap);
        Self { ptr, len: 0, cap }
    }

    /// Creates an `AlignedVec` from an existing `Vec<T>`, copying data into
    /// aligned storage. Requires `T: Copy` to ensure bitwise copy is sound.
    #[allow(unsafe_code)]
    pub fn from_vec(v: Vec<T>) -> Self
    where
        T: Copy,
    {
        let len = v.len();
        if len == 0 {
            return Self::new();
        }
        let ptr = alloc_aligned::<T>(len);
        // SAFETY: ptr is valid for len elements, v.as_ptr() is valid for len elements,
        // they do not overlap (fresh allocation).
        unsafe {
            std::ptr::copy_nonoverlapping(v.as_ptr(), ptr, len);
        }
        // v is dropped here normally — T: Copy so no element destructors,
        // and Vec's drop frees the backing allocation.
        drop(v);
        Self { ptr, len, cap: len }
    }

    /// Returns the number of elements.
    #[inline]
    pub const fn len(&self) -> usize {
        self.len
    }

    /// Returns `true` if the vec is empty.
    #[inline]
    pub const fn is_empty(&self) -> bool {
        self.len == 0
    }

    /// Returns a raw pointer to the aligned data.
    #[inline]
    pub const fn as_ptr(&self) -> *const T {
        self.ptr
    }

    /// Returns a mutable raw pointer to the aligned data.
    #[inline]
    pub const fn as_mut_ptr(&mut self) -> *mut T {
        self.ptr
    }

    /// Returns an immutable slice over the contained elements.
    #[inline]
    #[allow(unsafe_code)]
    pub const fn as_slice(&self) -> &[T] {
        if self.len == 0 {
            return &[];
        }
        // SAFETY: ptr is valid for self.len elements, properly aligned.
        unsafe { std::slice::from_raw_parts(self.ptr, self.len) }
    }

    /// Returns a mutable slice over the contained elements.
    #[inline]
    #[allow(unsafe_code)]
    pub const fn as_mut_slice(&mut self) -> &mut [T] {
        if self.len == 0 {
            return &mut [];
        }
        // SAFETY: ptr is valid for self.len elements, properly aligned, uniquely borrowed.
        unsafe { std::slice::from_raw_parts_mut(self.ptr, self.len) }
    }

    /// Appends a value to the end, growing if necessary.
    #[allow(unsafe_code)]
    pub fn push(&mut self, val: T) {
        if self.len == self.cap {
            self.grow();
        }
        // SAFETY: after grow, self.cap > self.len, so ptr.add(self.len) is valid.
        unsafe {
            self.ptr.add(self.len).write(val);
        }
        self.len += 1;
    }

    /// Grows the backing allocation (doubles capacity, minimum 4).
    #[allow(unsafe_code)]
    fn grow(&mut self) {
        let new_cap = if self.cap == 0 {
            4
        } else {
            self.cap.checked_mul(2).expect("capacity overflow")
        };
        let new_ptr = alloc_aligned::<T>(new_cap);
        if self.cap > 0 {
            if self.len > 0 {
                // SAFETY: old ptr valid for self.len elements, new ptr valid for new_cap >= self.len.
                unsafe {
                    std::ptr::copy_nonoverlapping(self.ptr, new_ptr, self.len);
                }
            }
            dealloc_aligned::<T>(self.ptr, self.cap);
        }
        self.ptr = new_ptr;
        self.cap = new_cap;
    }
}

impl<T: Copy> AlignedVec<T> {
    /// Creates an `AlignedVec` with `len` elements of **uninitialized** memory.
    ///
    /// The caller **must** write every element before reading any of them.
    /// This avoids the cost of zeroing the buffer when a subsequent SIMD pass
    /// will overwrite every element anyway.
    ///
    /// # Safety
    /// The allocation is valid and aligned, but the contents are indeterminate.
    /// The caller must initialize every element before any read or drop of the
    /// returned vector. Reading an uninitialized element is undefined behaviour.
    #[allow(unsafe_code)]
    #[inline]
    pub unsafe fn uninitialized(len: usize) -> Self {
        if len == 0 {
            return Self::new();
        }
        let ptr = alloc_aligned::<T>(len);
        Self { ptr, len, cap: len }
    }
}

impl<T: Default + Copy> AlignedVec<T> {
    /// Creates an `AlignedVec` of `len` elements, each set to `val`.
    #[allow(unsafe_code)]
    pub fn filled(len: usize, val: T) -> Self {
        if len == 0 {
            return Self::new();
        }
        let ptr = alloc_aligned::<T>(len);
        // SAFETY: ptr is valid for len elements.
        unsafe {
            for i in 0..len {
                ptr.add(i).write(val);
            }
        }
        Self { ptr, len, cap: len }
    }

    /// Creates an `AlignedVec` of `len` zero/default elements.
    pub fn zeros(len: usize) -> Self {
        Self::filled(len, T::default())
    }
}

impl<T: Zeroable> AlignedVec<T> {
    /// Creates an `AlignedVec` of `len` elements using an all-zero allocation.
    ///
    /// The [`Zeroable`] bound makes the representation guarantee explicit at
    /// the API boundary; arbitrary generic `T` can no longer be passed here.
    #[allow(unsafe_code)]
    pub fn calloc(len: usize) -> Self {
        if len == 0 {
            return Self::new();
        }
        let size = len
            .checked_mul(std::mem::size_of::<T>())
            .expect("allocation size overflow");
        let size = size.max(1);
        let align = align_for_size(size);
        let layout =
            std::alloc::Layout::from_size_align(size, align).expect("invalid allocation layout");
        // SAFETY: layout has non-zero size. alloc_zeroed returns zeroed memory.
        let ptr = unsafe { std::alloc::alloc_zeroed(layout) };
        if ptr.is_null() {
            std::alloc::handle_alloc_error(layout);
        }
        Self {
            ptr: ptr as *mut T,
            len,
            cap: len,
        }
    }
}

impl<T> Drop for AlignedVec<T> {
    #[allow(unsafe_code)]
    fn drop(&mut self) {
        if self.cap == 0 {
            return;
        }
        // Drop elements in place.
        unsafe {
            std::ptr::drop_in_place(std::ptr::slice_from_raw_parts_mut(self.ptr, self.len));
        }
        dealloc_aligned::<T>(self.ptr, self.cap);
    }
}

impl<T: Clone> Clone for AlignedVec<T> {
    #[allow(unsafe_code)]
    fn clone(&self) -> Self {
        if self.len == 0 {
            return Self::new();
        }
        let ptr = alloc_aligned::<T>(self.len);
        // SAFETY: ptr valid for self.len elements, we write each one via clone.
        unsafe {
            for i in 0..self.len {
                ptr.add(i).write((*self.ptr.add(i)).clone());
            }
        }
        Self {
            ptr,
            len: self.len,
            cap: self.len,
        }
    }
}

impl<T: fmt::Debug> fmt::Debug for AlignedVec<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_list().entries(self.as_slice().iter()).finish()
    }
}

impl<T: PartialEq> PartialEq for AlignedVec<T> {
    fn eq(&self, other: &Self) -> bool {
        self.as_slice() == other.as_slice()
    }
}

impl<T> Deref for AlignedVec<T> {
    type Target = [T];

    #[inline]
    fn deref(&self) -> &[T] {
        self.as_slice()
    }
}

impl<T> DerefMut for AlignedVec<T> {
    #[inline]
    fn deref_mut(&mut self) -> &mut [T] {
        self.as_mut_slice()
    }
}

impl<T> FromIterator<T> for AlignedVec<T> {
    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
        let iter = iter.into_iter();
        let (lower, _) = iter.size_hint();
        let mut v = AlignedVec::with_capacity(lower);
        for item in iter {
            v.push(item);
        }
        v
    }
}

// ── Allocation helpers ─────────────────────────────────────────────

/// Allocates aligned memory for `count` elements of type `T`.
/// Thread-local cache of freed aligned allocations.
/// Avoids repeated mmap/munmap for same-size buffers (like PyTorch's CachingAllocator).
/// Each entry: `(pointer, byte_size, alignment)`. The alignment is part of the
/// key so the cache never hands a 64B-aligned pointer back for a request that
/// needs a larger alignment — that would be undefined behaviour.
#[allow(unsafe_code)]
mod alloc_cache {

    use std::cell::RefCell;

    const MAX_CACHED: usize = 16;

    struct AllocCache {
        entries: Vec<(*mut u8, usize, usize)>,
    }

    impl AllocCache {
        const fn new() -> Self {
            Self {
                entries: Vec::new(),
            }
        }
    }

    impl Drop for AllocCache {
        fn drop(&mut self) {
            for &(ptr, size, align) in &self.entries {
                if !ptr.is_null()
                    && let Ok(layout) = std::alloc::Layout::from_size_align(size, align)
                {
                    unsafe {
                        std::alloc::dealloc(ptr, layout);
                    }
                }
            }
        }
    }

    thread_local! {
        static CACHE: RefCell<AllocCache> = const { RefCell::new(AllocCache::new()) };
    }

    pub(super) fn try_alloc(size: usize, align: usize) -> Option<*mut u8> {
        if cfg!(miri) {
            return None;
        }
        CACHE
            .try_with(|c| {
                let mut cache = c.borrow_mut();
                // Check last entry first (MRU — temporal locality for inference loops)
                if let Some(&(_, s, a)) = cache.entries.last()
                    && s == size
                    && a == align
                {
                    let (ptr, _, _) = cache.entries.pop().unwrap();
                    return Some(ptr);
                }
                // Fallback: linear scan
                if let Some(pos) = cache
                    .entries
                    .iter()
                    .position(|&(_, s, a)| s == size && a == align)
                {
                    let (ptr, _, _) = cache.entries.swap_remove(pos);
                    Some(ptr)
                } else {
                    None
                }
            })
            .ok()
            .flatten()
    }

    pub(super) fn try_dealloc(ptr: *mut u8, size: usize, align: usize) -> bool {
        if cfg!(miri) {
            return false;
        }
        CACHE
            .try_with(|c| {
                let mut cache = c.borrow_mut();
                if cache.entries.len() < MAX_CACHED {
                    cache.entries.push((ptr, size, align));
                    true
                } else {
                    false
                }
            })
            .unwrap_or(false)
    }
}

#[allow(unsafe_code)]
fn alloc_aligned<T>(count: usize) -> *mut T {
    assert!(count > 0, "cannot allocate zero-sized aligned buffer");
    let size = count
        .checked_mul(std::mem::size_of::<T>())
        .expect("allocation size overflow");
    let size = size.max(1);
    let align = align_for_size(size);

    // Try thread-local cache first — cache is keyed by (size, align) so we
    // only return a pointer that matches BOTH the requested size and align.
    if let Some(ptr) = alloc_cache::try_alloc(size, align) {
        return ptr as *mut T;
    }

    let layout =
        std::alloc::Layout::from_size_align(size, align).expect("invalid allocation layout");
    // SAFETY: layout has non-zero size.
    let ptr = unsafe { std::alloc::alloc(layout) };
    if ptr.is_null() {
        std::alloc::handle_alloc_error(layout);
    }
    ptr as *mut T
}

/// Deallocates aligned memory previously allocated with `alloc_aligned`.
#[allow(unsafe_code)]
fn dealloc_aligned<T>(ptr: *mut T, cap: usize) {
    let size = match cap.checked_mul(std::mem::size_of::<T>()) {
        Some(s) => s.max(1),
        None => return, // overflow — cannot reconstruct layout, leak rather than panic in Drop
    };
    let align = align_for_size(size);

    // Try to cache instead of freeing
    if alloc_cache::try_dealloc(ptr as *mut u8, size, align) {
        return;
    }

    if let Ok(layout) = std::alloc::Layout::from_size_align(size, align) {
        // SAFETY: ptr was allocated with this layout via alloc_aligned.
        unsafe {
            std::alloc::dealloc(ptr as *mut u8, layout);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn alignment_is_32_bytes() {
        let v = AlignedVec::<f32>::with_capacity(64);
        assert_eq!(v.as_ptr() as usize % 32, 0);
    }

    #[test]
    fn filled_and_len() {
        let v = AlignedVec::filled(100, 1.0f32);
        assert_eq!(v.len(), 100);
        assert!(v.iter().all(|&x| x == 1.0));
        assert_eq!(v.as_ptr() as usize % 32, 0);
    }

    #[test]
    fn zeros_default() {
        let v = AlignedVec::<f32>::zeros(16);
        assert_eq!(v.len(), 16);
        assert!(v.iter().all(|&x| x == 0.0));
    }

    #[test]
    fn from_vec_copies_and_aligns() {
        let orig = vec![1.0f32, 2.0, 3.0, 4.0];
        let aligned = AlignedVec::from_vec(orig);
        assert_eq!(aligned.as_slice(), &[1.0, 2.0, 3.0, 4.0]);
        assert_eq!(aligned.as_ptr() as usize % 32, 0);
    }

    #[test]
    fn push_and_grow() {
        let mut v = AlignedVec::<f32>::new();
        for i in 0..100 {
            v.push(i as f32);
        }
        assert_eq!(v.len(), 100);
        assert_eq!(v[50], 50.0);
        assert_eq!(v.as_ptr() as usize % 32, 0);
    }

    #[test]
    fn clone_preserves_alignment() {
        let v = AlignedVec::filled(10, 42.0f32);
        let v2 = v.clone();
        assert_eq!(v.as_slice(), v2.as_slice());
        assert_eq!(v2.as_ptr() as usize % 32, 0);
    }

    #[test]
    fn from_iterator() {
        let v: AlignedVec<f32> = (0..10).map(|i| i as f32).collect();
        assert_eq!(v.len(), 10);
        assert_eq!(v[5], 5.0);
        assert_eq!(v.as_ptr() as usize % 32, 0);
    }

    #[test]
    fn empty_vec_operations() {
        let v = AlignedVec::<f32>::new();
        assert!(v.is_empty());
        assert_eq!(v.len(), 0);
        assert_eq!(v.as_slice(), &[] as &[f32]);
    }

    #[test]
    fn deref_slice_access() {
        let v = AlignedVec::filled(5, 3.0f32);
        // Test that Deref to [T] works
        let sum: f32 = v.iter().sum();
        assert_eq!(sum, 15.0);
    }
}