singe-cuda 0.1.0-alpha.8

Safe Rust wrappers for CUDA driver, runtime, NVRTC, NVVM, NVTX, memory, streams, modules, and graphs.
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
//! Borrowed typed views over CUDA-accessible memory.

use std::{
    marker::PhantomData,
    mem::size_of,
    ops::{Bound, RangeBounds},
    ptr::NonNull,
};

use crate::{
    error::{Error, Result},
    memory::DeviceMemory,
    types::{Complex32, Complex64, bf16, f4e2m1, f6e2m3, f6e3m2, f8e4m3, f8e5m2, f8ue8m0, f16},
};

/// A Rust type that can be represented as plain CUDA device memory.
///
/// # Safety
///
/// Implementors must have a stable bit representation for device memory. Values
/// may be copied byte-for-byte between host and device memory without running
/// Rust destructors or relying on host-only pointer validity.
pub unsafe trait DeviceRepr: Copy + 'static {}

/// A [`DeviceRepr`] whose all-zero byte pattern is a valid value.
///
/// # Safety
///
/// Implementors must accept an all-zero byte pattern as a valid instance.
pub unsafe trait ZeroableDeviceRepr: DeviceRepr {}

macro_rules! impl_device_repr {
    ($($ty:ty),* $(,)?) => {
        $(
            unsafe impl DeviceRepr for $ty {}
            unsafe impl ZeroableDeviceRepr for $ty {}
        )*
    };
}

impl_device_repr!(
    bool, u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize, f32, f64, f16, bf16,
    Complex32, Complex64, f8e4m3, f8e5m2, f8ue8m0, f6e2m3, f6e3m2, f4e2m1,
);

/// A typed contiguous range of CUDA-accessible device memory.
pub trait DeviceSlice<T: DeviceRepr> {
    fn as_device_ptr(&self) -> *const T;

    fn len(&self) -> usize;

    fn is_empty(&self) -> bool {
        self.len() == 0
    }

    fn byte_len(&self) -> Result<usize> {
        self.len()
            .checked_mul(size_of::<T>())
            .ok_or(Error::InvalidMemoryAllocationRequest)
    }
}

/// A mutable typed contiguous range of CUDA-accessible device memory.
pub trait DeviceSliceMut<T: DeviceRepr>: DeviceSlice<T> {
    fn as_device_mut_ptr(&mut self) -> *mut T;
}

/// Shared abstraction for read-only typed device buffers.
pub trait DeviceBuffer<T: DeviceRepr>: DeviceSlice<T> {}

impl<T, B> DeviceBuffer<T> for B
where
    T: DeviceRepr,
    B: DeviceSlice<T> + ?Sized,
{
}

/// Shared abstraction for mutable typed device buffers.
pub trait DeviceBufferMut<T: DeviceRepr>: DeviceBuffer<T> + DeviceSliceMut<T> {}

impl<T, B> DeviceBufferMut<T> for B
where
    T: DeviceRepr,
    B: DeviceBuffer<T> + DeviceSliceMut<T> + ?Sized,
{
}

/// A typed contiguous host-memory range that can be copied to CUDA memory.
pub trait HostSlice<T: DeviceRepr> {
    fn as_host_ptr(&self) -> *const T;

    fn len(&self) -> usize;

    fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

/// A mutable typed contiguous host-memory range that can be copied from CUDA memory.
pub trait HostSliceMut<T: DeviceRepr>: HostSlice<T> {
    fn as_host_mut_ptr(&mut self) -> *mut T;
}

/// Shared abstraction for read-only host buffers.
pub trait HostBuffer<T: DeviceRepr>: HostSlice<T> {}

impl<T, B> HostBuffer<T> for B
where
    T: DeviceRepr,
    B: HostSlice<T> + ?Sized,
{
}

/// Shared abstraction for mutable host buffers.
pub trait HostBufferMut<T: DeviceRepr>: HostBuffer<T> + HostSliceMut<T> {}

impl<T, B> HostBufferMut<T> for B
where
    T: DeviceRepr,
    B: HostBuffer<T> + HostSliceMut<T> + ?Sized,
{
}

/// Shared abstraction for read-only byte buffers.
pub trait ByteBuffer {
    fn as_byte_ptr(&self) -> *const u8;

    fn byte_len(&self) -> usize;

    fn is_empty(&self) -> bool {
        self.byte_len() == 0
    }
}

/// Shared abstraction for mutable byte buffers.
pub trait ByteBufferMut: ByteBuffer {
    fn as_byte_mut_ptr(&mut self) -> *mut u8;
}

impl<B> ByteBuffer for B
where
    B: DeviceSlice<u8> + ?Sized,
{
    fn as_byte_ptr(&self) -> *const u8 {
        self.as_device_ptr()
    }

    fn byte_len(&self) -> usize {
        self.len()
    }
}

impl<B> ByteBufferMut for B
where
    B: DeviceSliceMut<u8> + ?Sized,
{
    fn as_byte_mut_ptr(&mut self) -> *mut u8 {
        self.as_device_mut_ptr()
    }
}

#[derive(Debug, Clone, Copy)]
/// Non-owning immutable view over CUDA-accessible device memory.
///
/// This type is `Copy` because it models a shared immutable borrow: duplicating
/// the view duplicates only the pointer/length pair and does not create or free
/// device memory. The lifetime ties the view to the allocation or owner that
/// created it, but CUDA kernels may still observe mutations performed through
/// other aliases according to CUDA stream ordering.
pub struct DeviceView<'a, T: DeviceRepr> {
    ptr: *const T,
    length: usize,
    _t: PhantomData<&'a T>,
}

#[derive(Debug)]
/// Non-owning mutable view over CUDA-accessible device memory.
///
/// This type is intentionally not `Clone` or `Copy` because it models a unique
/// mutable borrow of a device-memory range for the lifetime `'a`.
pub struct DeviceViewMut<'a, T: DeviceRepr> {
    ptr: *mut T,
    length: usize,
    _t: PhantomData<&'a mut T>,
}

impl<'a, T: DeviceRepr> DeviceView<'a, T> {
    /// Creates a borrowed immutable device view from a raw pointer and length.
    ///
    /// # Safety
    ///
    /// `ptr` must be valid for `length` contiguous elements of `T` for the
    /// returned lifetime. If `length` is zero, `ptr` may be null; the stored
    /// view pointer is normalized to `NonNull::dangling()` because safe
    /// borrowed views should not expose null unless a vendor API explicitly
    /// requires it. The memory must remain alive and CUDA-accessible while the
    /// view is used.
    pub const unsafe fn from_raw_parts(ptr: *const T, length: usize) -> Self {
        let ptr = if length == 0 {
            NonNull::<T>::dangling().as_ptr() as *const T
        } else {
            ptr
        };
        Self {
            ptr,
            length,
            _t: PhantomData,
        }
    }

    pub fn from_memory(memory: &'a DeviceMemory<T>) -> Self {
        Self {
            ptr: memory.as_ptr(),
            length: memory.len(),
            _t: PhantomData,
        }
    }

    pub const fn as_ptr(&self) -> *const T {
        self.ptr
    }

    pub const fn len(&self) -> usize {
        self.length
    }

    pub const fn is_empty(&self) -> bool {
        self.length == 0
    }

    pub fn slice<R: RangeBounds<usize>>(self, range: R) -> Result<Self> {
        let (start, end) = bounds_to_range(range, self.length)?;
        // Empty device allocations are represented by null pointers. Use
        // wrapping_add so slicing an empty view with a zero offset stays defined.
        let ptr = self.ptr.wrapping_add(start);
        Ok(Self {
            ptr,
            length: end - start,
            _t: PhantomData,
        })
    }
}

impl<'a, T: DeviceRepr> DeviceViewMut<'a, T> {
    /// Creates a borrowed mutable device view from a raw pointer and length.
    ///
    /// # Safety
    ///
    /// `ptr` must be valid for `length` contiguous mutable elements of `T` for
    /// the returned lifetime. If `length` is zero, `ptr` may be null; the
    /// stored view pointer is normalized to `NonNull::dangling()` because safe
    /// borrowed views should not expose null unless a vendor API explicitly
    /// requires it. The caller must guarantee unique access to the memory
    /// represented by the view.
    pub const unsafe fn from_raw_parts(ptr: *mut T, length: usize) -> Self {
        let ptr = if length == 0 {
            NonNull::<T>::dangling().as_ptr()
        } else {
            ptr
        };
        Self {
            ptr,
            length,
            _t: PhantomData,
        }
    }

    pub fn from_memory(memory: &'a mut DeviceMemory<T>) -> Self {
        Self {
            ptr: memory.as_mut_ptr(),
            length: memory.len(),
            _t: PhantomData,
        }
    }

    pub const fn as_ptr(&self) -> *const T {
        self.ptr
    }

    pub const fn as_mut_ptr(&mut self) -> *mut T {
        self.ptr
    }

    pub const fn len(&self) -> usize {
        self.length
    }

    pub const fn is_empty(&self) -> bool {
        self.length == 0
    }

    pub fn as_view(&self) -> DeviceView<'_, T> {
        DeviceView {
            ptr: self.ptr,
            length: self.length,
            _t: PhantomData,
        }
    }

    pub fn slice<R: RangeBounds<usize>>(&self, range: R) -> Result<DeviceView<'_, T>> {
        self.as_view().slice(range)
    }

    pub fn slice_mut<R: RangeBounds<usize>>(&mut self, range: R) -> Result<DeviceViewMut<'_, T>> {
        let (start, end) = bounds_to_range(range, self.length)?;
        // Empty device allocations are represented by null pointers. Use
        // wrapping_add so slicing an empty view with a zero offset stays defined.
        let ptr = self.ptr.wrapping_add(start);
        Ok(DeviceViewMut {
            ptr,
            length: end - start,
            _t: PhantomData,
        })
    }

    pub fn split_at_mut(
        &mut self,
        mid: usize,
    ) -> Result<(DeviceViewMut<'_, T>, DeviceViewMut<'_, T>)> {
        if mid > self.length {
            return Err(Error::InvalidMemoryAccess);
        }

        // See slice_mut: split_at_mut(0) must be valid for empty null views.
        let right = self.ptr.wrapping_add(mid);
        Ok((
            DeviceViewMut {
                ptr: self.ptr,
                length: mid,
                _t: PhantomData,
            },
            DeviceViewMut {
                ptr: right,
                length: self.length - mid,
                _t: PhantomData,
            },
        ))
    }
}

impl<T: DeviceRepr> DeviceMemory<T> {
    pub fn view(&self) -> DeviceView<'_, T> {
        DeviceView::from_memory(self)
    }

    pub fn view_mut(&mut self) -> DeviceViewMut<'_, T> {
        DeviceViewMut::from_memory(self)
    }
}

impl<T: DeviceRepr> DeviceSlice<T> for DeviceMemory<T> {
    fn as_device_ptr(&self) -> *const T {
        self.as_ptr()
    }

    fn len(&self) -> usize {
        self.len()
    }
}

impl<T: DeviceRepr> DeviceSliceMut<T> for DeviceMemory<T> {
    fn as_device_mut_ptr(&mut self) -> *mut T {
        self.as_mut_ptr()
    }
}

impl<T: DeviceRepr> DeviceSlice<T> for DeviceView<'_, T> {
    fn as_device_ptr(&self) -> *const T {
        self.ptr
    }

    fn len(&self) -> usize {
        self.length
    }
}

impl<T: DeviceRepr> DeviceSlice<T> for DeviceViewMut<'_, T> {
    fn as_device_ptr(&self) -> *const T {
        self.ptr
    }

    fn len(&self) -> usize {
        self.length
    }
}

impl<T: DeviceRepr> DeviceSliceMut<T> for DeviceViewMut<'_, T> {
    fn as_device_mut_ptr(&mut self) -> *mut T {
        self.ptr
    }
}

impl<T: DeviceRepr> HostSlice<T> for [T] {
    fn as_host_ptr(&self) -> *const T {
        self.as_ptr()
    }

    fn len(&self) -> usize {
        self.len()
    }
}

impl<T: DeviceRepr> HostSliceMut<T> for [T] {
    fn as_host_mut_ptr(&mut self) -> *mut T {
        self.as_mut_ptr()
    }
}

impl<T: DeviceRepr, const N: usize> HostSlice<T> for [T; N] {
    fn as_host_ptr(&self) -> *const T {
        self.as_ptr()
    }

    fn len(&self) -> usize {
        N
    }
}

impl<T: DeviceRepr, const N: usize> HostSliceMut<T> for [T; N] {
    fn as_host_mut_ptr(&mut self) -> *mut T {
        self.as_mut_ptr()
    }
}

impl<T: DeviceRepr> HostSlice<T> for Vec<T> {
    fn as_host_ptr(&self) -> *const T {
        self.as_ptr()
    }

    fn len(&self) -> usize {
        self.len()
    }
}

impl<T: DeviceRepr> HostSliceMut<T> for Vec<T> {
    fn as_host_mut_ptr(&mut self) -> *mut T {
        self.as_mut_ptr()
    }
}

fn bounds_to_range<R: RangeBounds<usize>>(range: R, length: usize) -> Result<(usize, usize)> {
    let start = match range.start_bound() {
        Bound::Included(&value) => value,
        Bound::Excluded(&value) => value.checked_add(1).ok_or(Error::InvalidMemoryAccess)?,
        Bound::Unbounded => 0,
    };
    let end = match range.end_bound() {
        Bound::Included(&value) => value.checked_add(1).ok_or(Error::InvalidMemoryAccess)?,
        Bound::Excluded(&value) => value,
        Bound::Unbounded => length,
    };

    if start > end || end > length {
        return Err(Error::InvalidMemoryAccess);
    }

    Ok((start, end))
}