tensr 0.1.3

A high-performance, cross-platform, multi-backend tensor/array library for Rust
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
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
use std::ptr::NonNull;

use rayon::prelude::*;

use crate::{
    array::traits::GetWriteableBuffer,
    backend::traits::{
        ContainerLength, ContainerScalarType, ContainerStorageType,
        OwnedStorage, ScalarAccessor, ScalarWriter, Storage,
    },
    dimension::dim::Dimension,
};

/// The number of bytes to align heap-allocated memory to.
///
/// The largest alignment (64 bytes) is required by AVX-512,
/// so we use this by default. Please create a pull request
/// or an issue if there is a reason to change this value.
pub const MEM_ALIGN: usize = 64;

/// A non-null pointer which can be used in parallel blocks
#[derive(Debug)]
pub struct HostNonNull<T>(pub NonNull<T>);
unsafe impl<T> Send for HostNonNull<T> {}
unsafe impl<T> Sync for HostNonNull<T> {}

impl<T> Copy for HostNonNull<T> {}

impl<T> Clone for HostNonNull<T> {
    fn clone(&self) -> Self {
        *self
    }
}

/// An [`OwnedStorage`] object for data in host memory
///
/// # Example
/// ```rust
/// use tensr::backend::host::host_storage::HostStorage;
///
/// let mut host_storage = HostStorage::<usize>::new(10);
/// assert_eq!(host_storage.length, 10);
///
/// for i in 0..host_storage.length {
///     host_storage[i] = i + 1;
/// }
///
/// assert_eq!(host_storage[0], 1);
/// assert_eq!(host_storage[9], 10);
///
/// assert_eq!(host_storage[2..6], [3, 4, 5, 6]);
/// assert_eq!(host_storage[6..=9], [7, 8, 9, 10]);
/// ```
pub struct HostStorage<T> {
    pub ptr: HostNonNull<T>,
    pub length: usize,
    pub free_on_drop: bool,
}

impl<T> Storage for HostStorage<T>
where
    T: Copy,
{
    type OwnedStorageType = Self;

    fn fill(&mut self, value: Self::Scalar) {
        (0..self.length).for_each(|i| self[i] = value);
    }

    unsafe fn set_no_free(&mut self) {}
}

impl<T> ContainerLength for HostStorage<T> {
    fn len(&self) -> usize {
        self.length
    }
}

impl<T> ContainerScalarType for HostStorage<T>
where
    T: Copy,
{
    type Scalar = T;
}

impl<T> ContainerStorageType for HostStorage<T>
where
    T: Copy,
{
    type Storage = Self;
}

impl<T> OwnedStorage for HostStorage<T>
where
    T: Copy,
{
    type Raw = HostNonNull<T>;

    fn new_from_shape<Dim>(shape: &Dim) -> Self
    where
        Dim: Dimension,
        Self::Scalar: Default,
    {
        Self::new(shape.len())
    }

    unsafe fn new_from_shape_uninit<Dim>(shape: &Dim) -> Self
    where
        Dim: Dimension,
    {
        Self::new_uninit(shape.len())
    }

    unsafe fn get_raw(&self) -> Self::Raw {
        self.ptr
    }
}

impl<T> HostStorage<T> {
    /// Create a new [`HostStorage`] object with `length` elements, all
    /// initialized to `T::default()`.
    ///
    /// # Example
    /// ```rust
    /// use tensr::backend::host::host_storage::HostStorage;
    ///
    /// let host_storage = HostStorage::<f32>::new(10);
    /// assert_eq!(host_storage.length, 10);
    ///
    /// for i in 0..host_storage.length {
    ///     assert_eq!(host_storage[i], 0.0);
    /// }
    /// ```
    ///
    /// # Panics
    ///
    /// Panics if the memory allocation fails
    #[must_use]
    pub fn new(length: usize) -> Self
    where
        T: Default,
    {
        unsafe {
            let data = std::alloc::alloc(
                std::alloc::Layout::from_size_align_unchecked(
                    length * core::mem::size_of::<T>(),
                    MEM_ALIGN,
                ),
            )
            .cast::<T>();

            // Initialise all elements to their default value
            for i in 0..length {
                *data.add(i) = T::default();
            }

            Self {
                ptr: HostNonNull(NonNull::new(data).unwrap()),
                length,
                free_on_drop: true,
            }
        }
    }

    /// Create a new [`HostStorage`] object with `length` elements, not
    /// initializing the memory. For trivial types, this might be fine, but
    /// for types which require construction, this may cause problems if you
    /// are not careful.
    ///
    /// # Example
    /// ```rust
    /// use tensr::backend::host::host_storage::HostStorage;
    ///
    /// let host_storage = unsafe { HostStorage::<f32>::new_uninit(10) };
    /// assert_eq!(host_storage.length, 10);
    /// ```
    ///
    /// # Safety
    ///
    /// Each element is uninitialized, and must be written to before being read
    ///
    /// # Panics
    ///
    /// Panics if the memory allocation fail
    #[must_use]
    pub unsafe fn new_uninit(length: usize) -> Self {
        let data =
            std::alloc::alloc(std::alloc::Layout::from_size_align_unchecked(
                length * core::mem::size_of::<T>(),
                MEM_ALIGN,
            ))
            .cast::<T>();

        Self {
            ptr: HostNonNull(NonNull::new(data).unwrap()),
            length,
            free_on_drop: false,
        }
    }

    pub fn take_as_vec(&mut self) -> Vec<T> {
        unsafe {
            // Set length to zero so we do not free data
            let length = self.length;
            self.length = 0;
            Vec::from_raw_parts(self.ptr.0.as_ptr(), length, length)
        }
    }
}

impl<T> HostStorage<T>
where
    T: Send + Sync,
{
    /// Create a parallel slice iterator over slices of length `slice_size`.
    ///
    /// If the length of the input is nto a multiple of the slice size, the
    /// remaining elements are ignored.
    #[must_use]
    pub fn slice_par_iter(
        &self,
        slice_size: usize,
    ) -> impl IndexedParallelIterator<Item = &[T]> + '_ {
        let simd_size = self.length / slice_size;
        (0..simd_size)
            .into_par_iter()
            .map(move |i| &self[i * slice_size..(i + 1) * slice_size])
    }

    /// Create a parallel mutable slice iterator with slices of length
    /// `slice_size`.
    ///
    /// If the length of the input is not a multiple of the slice size, the
    /// remaining elements are ignored.
    #[must_use]
    pub fn slice_mut_par_iter(
        &mut self,
        slice_size: usize,
    ) -> impl IndexedParallelIterator<Item = &mut [T]> + '_ {
        let elements = self.length / slice_size;
        (0..elements).into_par_iter().map_init(
            || self.ptr,
            move |ptr, i| {
                let start = i * slice_size;
                let end = (i + 1) * slice_size;

                unsafe {
                    std::slice::from_raw_parts_mut(
                        ptr.0.as_ptr().add(start),
                        end - start,
                    )
                }
            },
        )
    }
}

impl<T> ScalarAccessor for HostStorage<T>
where
    T: Copy,
{
    fn get_scalar(&self, index: usize) -> Self::Scalar {
        self[index]
    }
}

impl<T> ScalarWriter for HostStorage<T>
where
    T: Copy,
{
    fn write_scalar(&mut self, value: Self::Scalar, index: usize) {
        self[index] = value;
    }
}

impl<T> Drop for HostStorage<T> {
    fn drop(&mut self) {
        // If the length is zero, there is nothing to free
        if self.free_on_drop && self.length > 0 {
            // We can convert the data into a vec and drop that instead, so
            // the logic is handled by the STL
            drop(self.take_as_vec());
        }
    }
}

impl<T> std::ops::Index<usize> for HostStorage<T> {
    type Output = T;

    fn index(&self, index: usize) -> &Self::Output {
        #[cold]
        #[inline(never)]
        #[track_caller]
        fn assert_failed(index: usize, len: usize) -> ! {
            panic!("index (is {index}) must be <= len (is {len})");
        }

        #[cfg(debug_assertions)]
        if index >= self.length {
            assert_failed(index, self.length)
        }

        unsafe { self.ptr.0.as_ptr().add(index).as_ref().unwrap() }
    }
}

impl<T> std::ops::IndexMut<usize> for HostStorage<T> {
    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
        #[cold]
        #[inline(never)]
        #[track_caller]
        fn assert_failed(index: usize, len: usize) -> ! {
            panic!("index (is {index}) must be <= len (is {len})");
        }

        #[cfg(debug_assertions)]
        if index >= self.length {
            assert_failed(index, self.length)
        }

        unsafe { self.ptr.0.as_ptr().add(index).as_mut().unwrap() }
    }
}

impl<T> std::ops::Index<std::ops::Range<usize>> for HostStorage<T> {
    type Output = [T];

    fn index(&self, index: std::ops::Range<usize>) -> &Self::Output {
        #[cold]
        #[inline(never)]
        #[track_caller]
        fn assert_failed(index: usize, len: usize) -> ! {
            panic!("index (is {index}) must be <= len (is {len})");
        }

        if index.start >= self.length {
            assert_failed(index.start, self.length)
        }

        if index.end > self.length {
            assert_failed(index.end, self.length)
        }

        unsafe {
            std::slice::from_raw_parts(
                self.ptr.0.as_ptr().add(index.start),
                index.end - index.start,
            )
        }
    }
}

impl<T> std::ops::IndexMut<std::ops::Range<usize>> for HostStorage<T> {
    fn index_mut(
        &mut self,
        index: std::ops::Range<usize>,
    ) -> &mut Self::Output {
        #[cold]
        #[inline(never)]
        #[track_caller]
        fn assert_failed(index: usize, len: usize) -> ! {
            panic!("index (is {index}) must be <= len (is {len})");
        }

        if index.start >= self.length {
            assert_failed(index.start, self.length)
        }

        if index.end > self.length {
            assert_failed(index.end, self.length)
        }

        unsafe {
            std::slice::from_raw_parts_mut(
                self.ptr.0.as_ptr().add(index.start),
                index.end - index.start,
            )
        }
    }
}

impl<T> std::ops::Index<std::ops::RangeInclusive<usize>> for HostStorage<T> {
    type Output = [T];

    fn index(&self, index: std::ops::RangeInclusive<usize>) -> &Self::Output {
        let start = *index.start();
        let end = *index.end();

        #[cold]
        #[inline(never)]
        #[track_caller]
        fn assert_failed(index: usize, len: usize) -> ! {
            panic!("index (is {index}) must be <= len (is {len})");
        }

        if start >= self.length {
            assert_failed(start, self.length)
        }

        if end >= self.length {
            assert_failed(*index.end(), self.length)
        }

        unsafe {
            std::slice::from_raw_parts(
                self.ptr.0.as_ptr().add(*index.start()),
                end - start + 1,
            )
        }
    }
}

impl<T> GetWriteableBuffer for HostStorage<T> {
    type Buffer = HostNonNull<T>;

    unsafe fn get_buffer_and_set_no_free(
        &mut self,
        len: usize,
    ) -> Option<Self::Buffer> {
        if self.length >= len {
            self.free_on_drop = false;
            Some(self.ptr)
        } else {
            None
        }
    }
}

#[cfg(test)]
mod test {
    use std::hint::black_box;

    use super::*;

    macro_rules! test_all {
        ($macro_name:ident, $($type:ty),+) => {
            $(
                paste::paste! {
                    $macro_name!($type, [<$macro_name _ $type>]);
                }
            )+
        };
    }

    macro_rules! test_all_fundamental {
        ($macro_name:ident) => {
            test_all!($macro_name, i16, i32, i64, u16, u32, u64, f32, f64);
        };
    }

    macro_rules! test_alloc {
        ($type:ty, $name:ident) => {
            #[test]
            fn $name() {
                let n = 1000;
                let s = HostStorage::<$type>::new(n);
                assert_eq!(s.length, n);

                // Assert alignment is correct
                assert_eq!((s.ptr.0.as_ptr() as usize) % MEM_ALIGN, 0);

                for i in 0..s.length {
                    type Type = $type;
                    assert_eq!(s[i], { Type::default() });
                }
            }
        };
    }

    macro_rules! test_alloc_uninit {
        ($type:ty, $name:ident) => {
            #[test]
            fn $name() {
                let n = 1000;
                let mut s = unsafe { HostStorage::<$type>::new_uninit(n) };
                assert_eq!(s.length, n);

                // Assert alignment is correct
                assert_eq!((s.ptr.0.as_ptr() as usize) % MEM_ALIGN, 0);

                // Check we can write to this data without segfaulting
                for i in 0..s.length {
                    type Type = $type;
                    s[i] = Type::default();
                    assert_eq!(s[i], Type::default());
                }
            }
        };
    }

    macro_rules! test_take_as_vec {
        ($type:ty, $name:ident) => {
            #[test]
            fn $name() {
                let n = 1000;
                let mut v = Vec::new();

                // Drop s to check the memory is not freed
                {
                    let mut s = HostStorage::<$type>::new(n);
                    v = s.take_as_vec();
                    drop(s);
                }

                assert_eq!(v.len(), n);

                // Check all values are valid and correct
                for i in 0..v.len() {
                    type Type = $type;
                    assert_eq!(v[i], { Type::default() });
                }
            }
        };
    }

    macro_rules! test_slice_par_iter {
        ($type:ty, $name:ident) => {
            #[test]
            fn $name() {
                let slice_width = 4;
                let n_slices = 1000;
                let n = n_slices * slice_width;
                let s = HostStorage::<$type>::new(n);

                type Type = $type;

                (0..n)
                    .into_par_iter()
                    .zip(s.slice_par_iter(slice_width))
                    .for_each(|(_, slice)| {
                        for i in 0..slice_width {
                            assert_eq!(slice[i], Type::default());
                        }
                    });
            }
        };
    }

    macro_rules! test_slice_mut_par_iter {
        ($type:ty, $name:ident) => {
            #[test]
            fn $name() {
                let slice_width = 4;
                let n_slices = 1000;
                let n = n_slices * slice_width;
                let mut s = unsafe { HostStorage::<$type>::new_uninit(n) };

                type Type = $type;

                (0..n)
                    .into_par_iter()
                    .zip(s.slice_mut_par_iter(slice_width))
                    .for_each(|(_, slice)| {
                        for i in 0..slice_width {
                            slice[i] = Type::default();
                            assert_eq!(slice[i], Type::default());
                        }
                    });
            }
        };
    }

    macro_rules! test_drop {
        ($type:ty, $name:ident) => {
            #[test]
            fn $name() {
                let n = 8196;

                // Create a LOT of these and see if the system runs out of
                // memory...
                for _ in 0..10_000 {
                    let s = black_box(HostStorage::<$type>::new(n));
                    drop(s);
                }
            }
        };
    }

    test_all_fundamental!(test_alloc);
    test_all_fundamental!(test_alloc_uninit);
    test_all_fundamental!(test_take_as_vec);
    test_all_fundamental!(test_slice_par_iter);
    test_all_fundamental!(test_slice_mut_par_iter);
    test_all_fundamental!(test_drop);
}