singe-cuda 0.1.0

Safe Rust wrappers for the CUDA driver and runtime APIs, including runtime compilation of CUDA C++ and NVTX annotations.
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
use std::{
    fmt::{self, Formatter},
    marker::PhantomData,
    mem::{MaybeUninit, align_of, size_of},
    ptr,
};

use crate::{
    memory::{DeviceMemory, ManagedMemory},
    view::{DeviceInputView, DeviceRange, DeviceRepr, DeviceSliceMut, DeviceView, DeviceViewMut},
};

/// Dynamically built CUDA kernel argument list.
///
/// Use this builder when the argument list depends on runtime conditions:
///
/// ```ignore
/// let mut params = KernelParameters::new();
/// params.arg(&input_ptr).arg(&output_ptr).push(len);
/// // SAFETY: the buffers match the kernel's parameters and outlive the launch.
/// unsafe { function.launch_async(&config, params, &stream)? };
/// ```
///
/// For fixed argument lists, passing a tuple of references directly to [`KernelFunction::launch_async`](super::KernelFunction::launch_async) avoids building a dynamic list:
///
/// ```ignore
/// // SAFETY: the buffers match the kernel's parameters and outlive the launch.
/// unsafe { function.launch_async(&config, (&input_ptr, &mut output_ptr, &len), &stream)? };
/// ```
///
/// Borrowed arguments are tied to the lifetime of this list.
/// Owned scalar and pointer arguments pushed with [`Self::push`] or [`Self::owned_arg`] are stored inline when they fit, so ordinary kernel launches do not allocate per argument.
pub struct KernelParameters<'a> {
    arguments: Vec<KernelParameter<'a>>,
}

const INLINE_KERNEL_ARGUMENTS: usize = 16;
const INLINE_KERNEL_ARGUMENT_BYTES: usize = 16;

mod private {
    #[expect(
        unnameable_types,
        reason = "sealed supertrait that other crates must not name or implement"
    )]
    pub trait Sealed {}
}

/// Appends a value to a CUDA kernel parameter list.
///
/// Implementations convert Rust wrapper types into the value a CUDA kernel sees at the ABI boundary, such as a scalar or device pointer.
pub trait PushKernelArg {
    /// Appends this value in the kernel ABI representation selected by its implementation.
    fn push_to(self, params: &mut KernelParameters<'_>);
}

/// Kernel launch arguments accepted by launch and graph-node APIs.
///
/// This sealed trait is implemented for [`KernelParameters`], `()`, and tuples of shared or mutable references up to 16 elements.
pub trait KernelLaunchArgs<'a>: private::Sealed {
    #[doc(hidden)]
    fn with_encoded_arguments<R>(self, f: impl FnOnce(EncodedKernelArgs<'_>) -> R) -> R;
}

/// Encoded CUDA kernel arguments for one launch or graph-node update call.
///
/// This is an implementation detail of [`KernelLaunchArgs`].
/// CUDA receives a temporary array of pointers to encoded argument values; callers should use [`KernelParameters`] or generated launch methods instead of constructing raw argument arrays directly.
#[derive(Debug)]
#[doc(hidden)]
pub struct EncodedKernelArgs<'a> {
    pointers: &'a mut [*mut ()],
}

trait KernelTupleArgument<'a> {
    fn into_kernel_argument_ptr(self) -> *mut ();
}

enum KernelParameter<'a> {
    Borrowed {
        ptr: *mut (),
        _marker: PhantomData<&'a ()>,
    },
    Owned(OwnedKernelArgument),
}

impl fmt::Debug for KernelParameter<'_> {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            Self::Borrowed { ptr, .. } => f.debug_tuple("Borrowed").field(ptr).finish(),
            Self::Owned(value) => f.debug_tuple("Owned").field(value).finish(),
        }
    }
}

enum OwnedKernelArgument {
    Inline(InlineKernelArgument),
    Boxed(Box<dyn KernelArgumentStorage>),
}

impl fmt::Debug for OwnedKernelArgument {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            Self::Inline(value) => f.debug_tuple("Inline").field(value).finish(),
            Self::Boxed(_) => f.debug_tuple("Boxed").finish_non_exhaustive(),
        }
    }
}

trait KernelArgumentStorage {
    fn as_mut_ptr(&mut self) -> *mut ();
}

impl<T> KernelArgumentStorage for T {
    fn as_mut_ptr(&mut self) -> *mut () {
        ptr::from_mut(self).cast()
    }
}

#[derive(Clone, Copy)]
#[repr(C, align(16))]
struct InlineKernelArgument {
    bytes: [MaybeUninit<u8>; INLINE_KERNEL_ARGUMENT_BYTES],
}

impl fmt::Debug for InlineKernelArgument {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.debug_struct("InlineKernelArgument")
            .finish_non_exhaustive()
    }
}

impl fmt::Debug for KernelParameters<'_> {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.debug_struct("KernelParameters")
            .field("arguments", &self.arguments.len())
            .finish()
    }
}

impl<'a> KernelParameters<'a> {
    /// Creates an empty kernel argument list.
    #[must_use]
    pub const fn new() -> Self {
        Self {
            arguments: Vec::new(),
        }
    }

    /// Appends a borrowed argument value without converting its Rust representation.
    ///
    /// The value stays borrowed for this list's lifetime.
    /// If it contains a device pointer, the borrow covers the pointer value rather than the pointed-to allocation.
    pub fn arg<T: 'a>(&mut self, value: &'a T) -> &mut Self {
        self.arguments.push(KernelParameter::Borrowed {
            ptr: ptr::from_ref(value).cast_mut().cast::<()>(),
            _marker: PhantomData,
        });
        self
    }

    /// Appends an exclusively borrowed argument value without converting its Rust representation.
    ///
    /// CUDA reads the value as a kernel argument; this does not request a write back to the host argument slot.
    /// A pointer argument still needs the pointee lifetime and access guarantees required by the launch.
    pub fn arg_mut<T: 'a>(&mut self, value: &'a mut T) -> &mut Self {
        self.arguments.push(KernelParameter::Borrowed {
            ptr: ptr::from_mut(value).cast::<()>(),
            _marker: PhantomData,
        });
        self
    }

    /// Pushes a copied kernel argument whose storage is owned by this list.
    ///
    /// Small scalar and pointer values are stored inline.
    /// Larger values fall back to heap storage, while keeping the argument pointee stable until CUDA has copied it during launch or graph-node creation.
    pub fn owned_arg<T: Copy + 'static>(&mut self, value: T) -> &mut Self {
        let value = OwnedKernelArgument::from_value(value);
        self.arguments.push(KernelParameter::Owned(value));
        self
    }

    /// Appends an argument using its [`PushKernelArg`] implementation to encode the kernel ABI value.
    pub fn push<A: PushKernelArg>(&mut self, arg: A) -> &mut Self {
        arg.push_to(self);
        self
    }

    /// Encodes a device input address, including deferred graph inputs.
    ///
    /// This copies metadata only.
    /// The launch contract determines when the pointed-to values must be initialized and how access is ordered.
    pub fn device_input<T: DeviceRepr, S: DeviceRange<T> + ?Sized>(
        &mut self,
        slice: &S,
    ) -> &mut Self {
        // Kernels take the device address for slice-like wrappers; length is a
        // separate scalar argument when the kernel needs it.
        self.owned_arg(slice.as_device_ptr())
    }

    /// Appends a copied device address for a mutable slice.
    ///
    /// This does not append the slice length or retain the allocation.
    /// Keep the allocation alive and preserve exclusive writable access for every execution that uses the copied pointer.
    pub fn device_slice_mut<T: DeviceRepr, S: DeviceSliceMut<T> + ?Sized>(
        &mut self,
        slice: &mut S,
    ) -> &mut Self {
        self.owned_arg(slice.as_mut_ptr())
    }

    fn raw_pointers(&mut self) -> RawKernelPointers {
        RawKernelPointers::from_parameters(self.arguments.as_mut_slice())
    }
}

impl KernelParameter<'_> {
    fn as_mut_ptr(&mut self) -> *mut () {
        match self {
            Self::Borrowed { ptr, .. } => *ptr,
            Self::Owned(value) => value.as_mut_ptr(),
        }
    }
}

impl OwnedKernelArgument {
    fn from_value<T: Copy + 'static>(value: T) -> Self {
        InlineKernelArgument::from_value(value)
            .map_or_else(|| Self::Boxed(Box::new(value)), Self::Inline)
    }

    fn as_mut_ptr(&mut self) -> *mut () {
        match self {
            Self::Inline(value) => value.as_mut_ptr(),
            Self::Boxed(value) => value.as_mut().as_mut_ptr(),
        }
    }
}

impl InlineKernelArgument {
    /// Stores `value` inline, or returns `None` if it does not fit the inline storage.
    fn from_value<T: Copy>(value: T) -> Option<Self> {
        if size_of::<T>() > INLINE_KERNEL_ARGUMENT_BYTES || align_of::<T>() > align_of::<Self>() {
            return None;
        }

        let mut storage = Self {
            bytes: [MaybeUninit::uninit(); INLINE_KERNEL_ARGUMENT_BYTES],
        };
        // SAFETY: the checks above guarantee the storage is large enough and aligned for `T`.
        unsafe {
            ptr::write(storage.as_mut_ptr().cast::<T>(), value);
        }
        Some(storage)
    }

    fn as_mut_ptr(&mut self) -> *mut () {
        self.bytes.as_mut_ptr().cast()
    }
}

enum RawKernelPointers {
    Inline {
        pointers: [*mut (); INLINE_KERNEL_ARGUMENTS],
        len: usize,
    },
    Heap(Vec<*mut ()>),
}

impl RawKernelPointers {
    fn from_parameters(parameters: &mut [KernelParameter<'_>]) -> Self {
        if parameters.len() <= INLINE_KERNEL_ARGUMENTS {
            let mut pointers = [ptr::null_mut(); INLINE_KERNEL_ARGUMENTS];
            for (dst, parameter) in pointers.iter_mut().zip(&mut *parameters) {
                *dst = parameter.as_mut_ptr();
            }
            Self::Inline {
                pointers,
                len: parameters.len(),
            }
        } else {
            Self::Heap(
                parameters
                    .iter_mut()
                    .map(KernelParameter::as_mut_ptr)
                    .collect(),
            )
        }
    }

    fn as_mut_slice(&mut self) -> &mut [*mut ()] {
        match self {
            Self::Inline { pointers, len } => &mut pointers[..*len],
            Self::Heap(pointers) => pointers.as_mut_slice(),
        }
    }
}

impl EncodedKernelArgs<'_> {
    pub(crate) fn as_mut_ptr(&mut self) -> *mut *mut () {
        self.pointers.as_mut_ptr()
    }
}

impl<'a> KernelLaunchArgs<'a> for KernelParameters<'a> {
    fn with_encoded_arguments<R>(mut self, f: impl FnOnce(EncodedKernelArgs<'_>) -> R) -> R {
        let mut pointers = self.raw_pointers();
        f(EncodedKernelArgs {
            pointers: pointers.as_mut_slice(),
        })
    }
}

impl private::Sealed for KernelParameters<'_> {}

impl<'a> KernelLaunchArgs<'a> for &mut KernelParameters<'a> {
    fn with_encoded_arguments<R>(self, f: impl FnOnce(EncodedKernelArgs<'_>) -> R) -> R {
        let mut pointers = self.raw_pointers();
        f(EncodedKernelArgs {
            pointers: pointers.as_mut_slice(),
        })
    }
}

impl private::Sealed for &mut KernelParameters<'_> {}

impl KernelLaunchArgs<'_> for () {
    fn with_encoded_arguments<R>(self, f: impl FnOnce(EncodedKernelArgs<'_>) -> R) -> R {
        let mut pointers: [*mut (); 0] = [];
        f(EncodedKernelArgs {
            pointers: &mut pointers,
        })
    }
}

impl private::Sealed for () {}

macro_rules! impl_kernel_arguments_for_tuple {
    ($($arg:ident),+ $(,)?) => {
        impl<'a, $($arg),+> private::Sealed for ($($arg,)+)
        where
            $($arg: KernelTupleArgument<'a>,)+
        {
        }

        impl<'a, $($arg),+> KernelLaunchArgs<'a> for ($($arg,)+)
        where
            $($arg: KernelTupleArgument<'a>,)+
        {
            fn with_encoded_arguments<R>(self, f: impl FnOnce(EncodedKernelArgs<'_>) -> R) -> R {
                #[allow(non_snake_case, reason = "tuple fields are bound to the macro's uppercase type parameter names")]
                let ($($arg,)+) = self;
                let mut pointers = [
                    $($arg.into_kernel_argument_ptr(),)+
                ];
                f(EncodedKernelArgs {
                    pointers: &mut pointers,
                })
            }
        }
    };
}

impl<'a, T: 'a> KernelTupleArgument<'a> for &'a T {
    fn into_kernel_argument_ptr(self) -> *mut () {
        ptr::from_ref(self).cast_mut().cast()
    }
}

impl<'a, T: 'a> KernelTupleArgument<'a> for &'a mut T {
    fn into_kernel_argument_ptr(self) -> *mut () {
        ptr::from_mut(self).cast()
    }
}

impl_kernel_arguments_for_tuple!(A);

impl_kernel_arguments_for_tuple!(A, B);

impl_kernel_arguments_for_tuple!(A, B, C);

impl_kernel_arguments_for_tuple!(A, B, C, D);

impl_kernel_arguments_for_tuple!(A, B, C, D, E);

impl_kernel_arguments_for_tuple!(A, B, C, D, E, F);

impl_kernel_arguments_for_tuple!(A, B, C, D, E, F, G);

impl_kernel_arguments_for_tuple!(A, B, C, D, E, F, G, H);

impl_kernel_arguments_for_tuple!(A, B, C, D, E, F, G, H, I);

impl_kernel_arguments_for_tuple!(A, B, C, D, E, F, G, H, I, J);

impl_kernel_arguments_for_tuple!(A, B, C, D, E, F, G, H, I, J, K);

impl_kernel_arguments_for_tuple!(A, B, C, D, E, F, G, H, I, J, K, L);

impl_kernel_arguments_for_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M);

impl_kernel_arguments_for_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M, N);

impl_kernel_arguments_for_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O);

impl_kernel_arguments_for_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P);

macro_rules! impl_push_scalar {
    ($($ty:ty),* $(,)?) => {
        $(
            impl PushKernelArg for $ty {
                fn push_to(self, params: &mut KernelParameters<'_>) {
                    params.owned_arg(self);
                }
            }
        )*
    };
}

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

impl<T: DeviceRepr> PushKernelArg for &DeviceMemory<T> {
    fn push_to(self, params: &mut KernelParameters<'_>) {
        params.device_input(self);
    }
}

impl<T: DeviceRepr> PushKernelArg for &mut DeviceMemory<T> {
    fn push_to(self, params: &mut KernelParameters<'_>) {
        params.device_slice_mut(self);
    }
}

impl<T: DeviceRepr> PushKernelArg for &ManagedMemory<T> {
    fn push_to(self, params: &mut KernelParameters<'_>) {
        params.device_input(self);
    }
}

impl<T: DeviceRepr> PushKernelArg for &mut ManagedMemory<T> {
    fn push_to(self, params: &mut KernelParameters<'_>) {
        params.device_slice_mut(self);
    }
}

impl<T: DeviceRepr> PushKernelArg for DeviceInputView<'_, T> {
    fn push_to(self, params: &mut KernelParameters<'_>) {
        params.device_input(&self);
    }
}

impl<T: DeviceRepr> PushKernelArg for &DeviceInputView<'_, T> {
    fn push_to(self, params: &mut KernelParameters<'_>) {
        params.device_input(self);
    }
}

impl<T: DeviceRepr> PushKernelArg for DeviceView<'_, T> {
    fn push_to(self, params: &mut KernelParameters<'_>) {
        params.owned_arg(self.as_ptr());
    }
}

impl<T: DeviceRepr> PushKernelArg for &DeviceView<'_, T> {
    fn push_to(self, params: &mut KernelParameters<'_>) {
        params.owned_arg(self.as_ptr());
    }
}

impl<T: DeviceRepr> PushKernelArg for &DeviceViewMut<'_, T> {
    fn push_to(self, params: &mut KernelParameters<'_>) {
        params.owned_arg(self.as_ptr());
    }
}

impl<T: DeviceRepr> PushKernelArg for &mut DeviceViewMut<'_, T> {
    fn push_to(self, params: &mut KernelParameters<'_>) {
        params.owned_arg(self.as_mut_ptr());
    }
}

impl Default for KernelParameters<'_> {
    fn default() -> Self {
        Self::new()
    }
}

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

    #[derive(Clone, Copy)]
    #[repr(C)]
    struct LargeArgument {
        words: [u64; 3],
    }

    #[test]
    fn test_boxed_owned_kernel_argument_points_to_inner_value() {
        let mut argument = OwnedKernelArgument::from_value(LargeArgument { words: [1, 2, 3] });
        assert!(matches!(argument, OwnedKernelArgument::Boxed(_)));

        let expected = match &mut argument {
            OwnedKernelArgument::Boxed(value) => value.as_mut().as_mut_ptr(),
            OwnedKernelArgument::Inline(_) => unreachable!(),
        };

        assert_eq!(argument.as_mut_ptr(), expected);
    }
}