Skip to main content

singe_cuda/module/
parameters.rs

1use std::{
2    fmt::{self, Formatter},
3    marker::PhantomData,
4    mem::{MaybeUninit, align_of, size_of},
5    ptr,
6};
7
8use crate::{
9    memory::{DeviceMemory, ManagedMemory},
10    view::{DeviceInputView, DeviceRange, DeviceRepr, DeviceSliceMut, DeviceView, DeviceViewMut},
11};
12
13/// Dynamically built CUDA kernel argument list.
14///
15/// Use this builder when the argument list depends on runtime conditions:
16///
17/// ```ignore
18/// let mut params = KernelParameters::new();
19/// params.arg(&input_ptr).arg(&output_ptr).push(len);
20/// // SAFETY: the buffers match the kernel's parameters and outlive the launch.
21/// unsafe { function.launch_async(&config, params, &stream)? };
22/// ```
23///
24/// For fixed argument lists, passing a tuple of references directly to [`KernelFunction::launch_async`](super::KernelFunction::launch_async) avoids building a dynamic list:
25///
26/// ```ignore
27/// // SAFETY: the buffers match the kernel's parameters and outlive the launch.
28/// unsafe { function.launch_async(&config, (&input_ptr, &mut output_ptr, &len), &stream)? };
29/// ```
30///
31/// Borrowed arguments are tied to the lifetime of this list.
32/// 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.
33pub struct KernelParameters<'a> {
34    arguments: Vec<KernelParameter<'a>>,
35}
36
37const INLINE_KERNEL_ARGUMENTS: usize = 16;
38const INLINE_KERNEL_ARGUMENT_BYTES: usize = 16;
39
40mod private {
41    #[expect(
42        unnameable_types,
43        reason = "sealed supertrait that other crates must not name or implement"
44    )]
45    pub trait Sealed {}
46}
47
48/// Appends a value to a CUDA kernel parameter list.
49///
50/// Implementations convert Rust wrapper types into the value a CUDA kernel sees at the ABI boundary, such as a scalar or device pointer.
51pub trait PushKernelArg {
52    /// Appends this value in the kernel ABI representation selected by its implementation.
53    fn push_to(self, params: &mut KernelParameters<'_>);
54}
55
56/// Kernel launch arguments accepted by launch and graph-node APIs.
57///
58/// This sealed trait is implemented for [`KernelParameters`], `()`, and tuples of shared or mutable references up to 16 elements.
59pub trait KernelLaunchArgs<'a>: private::Sealed {
60    #[doc(hidden)]
61    fn with_encoded_arguments<R>(self, f: impl FnOnce(EncodedKernelArgs<'_>) -> R) -> R;
62}
63
64/// Encoded CUDA kernel arguments for one launch or graph-node update call.
65///
66/// This is an implementation detail of [`KernelLaunchArgs`].
67/// 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.
68#[derive(Debug)]
69#[doc(hidden)]
70pub struct EncodedKernelArgs<'a> {
71    pointers: &'a mut [*mut ()],
72}
73
74trait KernelTupleArgument<'a> {
75    fn into_kernel_argument_ptr(self) -> *mut ();
76}
77
78enum KernelParameter<'a> {
79    Borrowed {
80        ptr: *mut (),
81        _marker: PhantomData<&'a ()>,
82    },
83    Owned(OwnedKernelArgument),
84}
85
86impl fmt::Debug for KernelParameter<'_> {
87    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
88        match self {
89            Self::Borrowed { ptr, .. } => f.debug_tuple("Borrowed").field(ptr).finish(),
90            Self::Owned(value) => f.debug_tuple("Owned").field(value).finish(),
91        }
92    }
93}
94
95enum OwnedKernelArgument {
96    Inline(InlineKernelArgument),
97    Boxed(Box<dyn KernelArgumentStorage>),
98}
99
100impl fmt::Debug for OwnedKernelArgument {
101    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
102        match self {
103            Self::Inline(value) => f.debug_tuple("Inline").field(value).finish(),
104            Self::Boxed(_) => f.debug_tuple("Boxed").finish_non_exhaustive(),
105        }
106    }
107}
108
109trait KernelArgumentStorage {
110    fn as_mut_ptr(&mut self) -> *mut ();
111}
112
113impl<T> KernelArgumentStorage for T {
114    fn as_mut_ptr(&mut self) -> *mut () {
115        ptr::from_mut(self).cast()
116    }
117}
118
119#[derive(Clone, Copy)]
120#[repr(C, align(16))]
121struct InlineKernelArgument {
122    bytes: [MaybeUninit<u8>; INLINE_KERNEL_ARGUMENT_BYTES],
123}
124
125impl fmt::Debug for InlineKernelArgument {
126    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
127        f.debug_struct("InlineKernelArgument")
128            .finish_non_exhaustive()
129    }
130}
131
132impl fmt::Debug for KernelParameters<'_> {
133    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
134        f.debug_struct("KernelParameters")
135            .field("arguments", &self.arguments.len())
136            .finish()
137    }
138}
139
140impl<'a> KernelParameters<'a> {
141    /// Creates an empty kernel argument list.
142    #[must_use]
143    pub const fn new() -> Self {
144        Self {
145            arguments: Vec::new(),
146        }
147    }
148
149    /// Appends a borrowed argument value without converting its Rust representation.
150    ///
151    /// The value stays borrowed for this list's lifetime.
152    /// If it contains a device pointer, the borrow covers the pointer value rather than the pointed-to allocation.
153    pub fn arg<T: 'a>(&mut self, value: &'a T) -> &mut Self {
154        self.arguments.push(KernelParameter::Borrowed {
155            ptr: ptr::from_ref(value).cast_mut().cast::<()>(),
156            _marker: PhantomData,
157        });
158        self
159    }
160
161    /// Appends an exclusively borrowed argument value without converting its Rust representation.
162    ///
163    /// CUDA reads the value as a kernel argument; this does not request a write back to the host argument slot.
164    /// A pointer argument still needs the pointee lifetime and access guarantees required by the launch.
165    pub fn arg_mut<T: 'a>(&mut self, value: &'a mut T) -> &mut Self {
166        self.arguments.push(KernelParameter::Borrowed {
167            ptr: ptr::from_mut(value).cast::<()>(),
168            _marker: PhantomData,
169        });
170        self
171    }
172
173    /// Pushes a copied kernel argument whose storage is owned by this list.
174    ///
175    /// Small scalar and pointer values are stored inline.
176    /// Larger values fall back to heap storage, while keeping the argument pointee stable until CUDA has copied it during launch or graph-node creation.
177    pub fn owned_arg<T: Copy + 'static>(&mut self, value: T) -> &mut Self {
178        let value = OwnedKernelArgument::from_value(value);
179        self.arguments.push(KernelParameter::Owned(value));
180        self
181    }
182
183    /// Appends an argument using its [`PushKernelArg`] implementation to encode the kernel ABI value.
184    pub fn push<A: PushKernelArg>(&mut self, arg: A) -> &mut Self {
185        arg.push_to(self);
186        self
187    }
188
189    /// Encodes a device input address, including deferred graph inputs.
190    ///
191    /// This copies metadata only.
192    /// The launch contract determines when the pointed-to values must be initialized and how access is ordered.
193    pub fn device_input<T: DeviceRepr, S: DeviceRange<T> + ?Sized>(
194        &mut self,
195        slice: &S,
196    ) -> &mut Self {
197        // Kernels take the device address for slice-like wrappers; length is a
198        // separate scalar argument when the kernel needs it.
199        self.owned_arg(slice.as_device_ptr())
200    }
201
202    /// Appends a copied device address for a mutable slice.
203    ///
204    /// This does not append the slice length or retain the allocation.
205    /// Keep the allocation alive and preserve exclusive writable access for every execution that uses the copied pointer.
206    pub fn device_slice_mut<T: DeviceRepr, S: DeviceSliceMut<T> + ?Sized>(
207        &mut self,
208        slice: &mut S,
209    ) -> &mut Self {
210        self.owned_arg(slice.as_mut_ptr())
211    }
212
213    fn raw_pointers(&mut self) -> RawKernelPointers {
214        RawKernelPointers::from_parameters(self.arguments.as_mut_slice())
215    }
216}
217
218impl KernelParameter<'_> {
219    fn as_mut_ptr(&mut self) -> *mut () {
220        match self {
221            Self::Borrowed { ptr, .. } => *ptr,
222            Self::Owned(value) => value.as_mut_ptr(),
223        }
224    }
225}
226
227impl OwnedKernelArgument {
228    fn from_value<T: Copy + 'static>(value: T) -> Self {
229        InlineKernelArgument::from_value(value)
230            .map_or_else(|| Self::Boxed(Box::new(value)), Self::Inline)
231    }
232
233    fn as_mut_ptr(&mut self) -> *mut () {
234        match self {
235            Self::Inline(value) => value.as_mut_ptr(),
236            Self::Boxed(value) => value.as_mut().as_mut_ptr(),
237        }
238    }
239}
240
241impl InlineKernelArgument {
242    /// Stores `value` inline, or returns `None` if it does not fit the inline storage.
243    fn from_value<T: Copy>(value: T) -> Option<Self> {
244        if size_of::<T>() > INLINE_KERNEL_ARGUMENT_BYTES || align_of::<T>() > align_of::<Self>() {
245            return None;
246        }
247
248        let mut storage = Self {
249            bytes: [MaybeUninit::uninit(); INLINE_KERNEL_ARGUMENT_BYTES],
250        };
251        // SAFETY: the checks above guarantee the storage is large enough and aligned for `T`.
252        unsafe {
253            ptr::write(storage.as_mut_ptr().cast::<T>(), value);
254        }
255        Some(storage)
256    }
257
258    fn as_mut_ptr(&mut self) -> *mut () {
259        self.bytes.as_mut_ptr().cast()
260    }
261}
262
263enum RawKernelPointers {
264    Inline {
265        pointers: [*mut (); INLINE_KERNEL_ARGUMENTS],
266        len: usize,
267    },
268    Heap(Vec<*mut ()>),
269}
270
271impl RawKernelPointers {
272    fn from_parameters(parameters: &mut [KernelParameter<'_>]) -> Self {
273        if parameters.len() <= INLINE_KERNEL_ARGUMENTS {
274            let mut pointers = [ptr::null_mut(); INLINE_KERNEL_ARGUMENTS];
275            for (dst, parameter) in pointers.iter_mut().zip(&mut *parameters) {
276                *dst = parameter.as_mut_ptr();
277            }
278            Self::Inline {
279                pointers,
280                len: parameters.len(),
281            }
282        } else {
283            Self::Heap(
284                parameters
285                    .iter_mut()
286                    .map(KernelParameter::as_mut_ptr)
287                    .collect(),
288            )
289        }
290    }
291
292    fn as_mut_slice(&mut self) -> &mut [*mut ()] {
293        match self {
294            Self::Inline { pointers, len } => &mut pointers[..*len],
295            Self::Heap(pointers) => pointers.as_mut_slice(),
296        }
297    }
298}
299
300impl EncodedKernelArgs<'_> {
301    pub(crate) fn as_mut_ptr(&mut self) -> *mut *mut () {
302        self.pointers.as_mut_ptr()
303    }
304}
305
306impl<'a> KernelLaunchArgs<'a> for KernelParameters<'a> {
307    fn with_encoded_arguments<R>(mut self, f: impl FnOnce(EncodedKernelArgs<'_>) -> R) -> R {
308        let mut pointers = self.raw_pointers();
309        f(EncodedKernelArgs {
310            pointers: pointers.as_mut_slice(),
311        })
312    }
313}
314
315impl private::Sealed for KernelParameters<'_> {}
316
317impl<'a> KernelLaunchArgs<'a> for &mut KernelParameters<'a> {
318    fn with_encoded_arguments<R>(self, f: impl FnOnce(EncodedKernelArgs<'_>) -> R) -> R {
319        let mut pointers = self.raw_pointers();
320        f(EncodedKernelArgs {
321            pointers: pointers.as_mut_slice(),
322        })
323    }
324}
325
326impl private::Sealed for &mut KernelParameters<'_> {}
327
328impl KernelLaunchArgs<'_> for () {
329    fn with_encoded_arguments<R>(self, f: impl FnOnce(EncodedKernelArgs<'_>) -> R) -> R {
330        let mut pointers: [*mut (); 0] = [];
331        f(EncodedKernelArgs {
332            pointers: &mut pointers,
333        })
334    }
335}
336
337impl private::Sealed for () {}
338
339macro_rules! impl_kernel_arguments_for_tuple {
340    ($($arg:ident),+ $(,)?) => {
341        impl<'a, $($arg),+> private::Sealed for ($($arg,)+)
342        where
343            $($arg: KernelTupleArgument<'a>,)+
344        {
345        }
346
347        impl<'a, $($arg),+> KernelLaunchArgs<'a> for ($($arg,)+)
348        where
349            $($arg: KernelTupleArgument<'a>,)+
350        {
351            fn with_encoded_arguments<R>(self, f: impl FnOnce(EncodedKernelArgs<'_>) -> R) -> R {
352                #[allow(non_snake_case, reason = "tuple fields are bound to the macro's uppercase type parameter names")]
353                let ($($arg,)+) = self;
354                let mut pointers = [
355                    $($arg.into_kernel_argument_ptr(),)+
356                ];
357                f(EncodedKernelArgs {
358                    pointers: &mut pointers,
359                })
360            }
361        }
362    };
363}
364
365impl<'a, T: 'a> KernelTupleArgument<'a> for &'a T {
366    fn into_kernel_argument_ptr(self) -> *mut () {
367        ptr::from_ref(self).cast_mut().cast()
368    }
369}
370
371impl<'a, T: 'a> KernelTupleArgument<'a> for &'a mut T {
372    fn into_kernel_argument_ptr(self) -> *mut () {
373        ptr::from_mut(self).cast()
374    }
375}
376
377impl_kernel_arguments_for_tuple!(A);
378
379impl_kernel_arguments_for_tuple!(A, B);
380
381impl_kernel_arguments_for_tuple!(A, B, C);
382
383impl_kernel_arguments_for_tuple!(A, B, C, D);
384
385impl_kernel_arguments_for_tuple!(A, B, C, D, E);
386
387impl_kernel_arguments_for_tuple!(A, B, C, D, E, F);
388
389impl_kernel_arguments_for_tuple!(A, B, C, D, E, F, G);
390
391impl_kernel_arguments_for_tuple!(A, B, C, D, E, F, G, H);
392
393impl_kernel_arguments_for_tuple!(A, B, C, D, E, F, G, H, I);
394
395impl_kernel_arguments_for_tuple!(A, B, C, D, E, F, G, H, I, J);
396
397impl_kernel_arguments_for_tuple!(A, B, C, D, E, F, G, H, I, J, K);
398
399impl_kernel_arguments_for_tuple!(A, B, C, D, E, F, G, H, I, J, K, L);
400
401impl_kernel_arguments_for_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M);
402
403impl_kernel_arguments_for_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M, N);
404
405impl_kernel_arguments_for_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O);
406
407impl_kernel_arguments_for_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P);
408
409macro_rules! impl_push_scalar {
410    ($($ty:ty),* $(,)?) => {
411        $(
412            impl PushKernelArg for $ty {
413                fn push_to(self, params: &mut KernelParameters<'_>) {
414                    params.owned_arg(self);
415                }
416            }
417        )*
418    };
419}
420
421impl_push_scalar!(
422    u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize, f32, f64,
423);
424
425impl<T: DeviceRepr> PushKernelArg for &DeviceMemory<T> {
426    fn push_to(self, params: &mut KernelParameters<'_>) {
427        params.device_input(self);
428    }
429}
430
431impl<T: DeviceRepr> PushKernelArg for &mut DeviceMemory<T> {
432    fn push_to(self, params: &mut KernelParameters<'_>) {
433        params.device_slice_mut(self);
434    }
435}
436
437impl<T: DeviceRepr> PushKernelArg for &ManagedMemory<T> {
438    fn push_to(self, params: &mut KernelParameters<'_>) {
439        params.device_input(self);
440    }
441}
442
443impl<T: DeviceRepr> PushKernelArg for &mut ManagedMemory<T> {
444    fn push_to(self, params: &mut KernelParameters<'_>) {
445        params.device_slice_mut(self);
446    }
447}
448
449impl<T: DeviceRepr> PushKernelArg for DeviceInputView<'_, T> {
450    fn push_to(self, params: &mut KernelParameters<'_>) {
451        params.device_input(&self);
452    }
453}
454
455impl<T: DeviceRepr> PushKernelArg for &DeviceInputView<'_, T> {
456    fn push_to(self, params: &mut KernelParameters<'_>) {
457        params.device_input(self);
458    }
459}
460
461impl<T: DeviceRepr> PushKernelArg for DeviceView<'_, T> {
462    fn push_to(self, params: &mut KernelParameters<'_>) {
463        params.owned_arg(self.as_ptr());
464    }
465}
466
467impl<T: DeviceRepr> PushKernelArg for &DeviceView<'_, T> {
468    fn push_to(self, params: &mut KernelParameters<'_>) {
469        params.owned_arg(self.as_ptr());
470    }
471}
472
473impl<T: DeviceRepr> PushKernelArg for &DeviceViewMut<'_, T> {
474    fn push_to(self, params: &mut KernelParameters<'_>) {
475        params.owned_arg(self.as_ptr());
476    }
477}
478
479impl<T: DeviceRepr> PushKernelArg for &mut DeviceViewMut<'_, T> {
480    fn push_to(self, params: &mut KernelParameters<'_>) {
481        params.owned_arg(self.as_mut_ptr());
482    }
483}
484
485impl Default for KernelParameters<'_> {
486    fn default() -> Self {
487        Self::new()
488    }
489}
490
491#[cfg(test)]
492mod tests {
493    use super::*;
494
495    #[derive(Clone, Copy)]
496    #[repr(C)]
497    struct LargeArgument {
498        words: [u64; 3],
499    }
500
501    #[test]
502    fn test_boxed_owned_kernel_argument_points_to_inner_value() {
503        let mut argument = OwnedKernelArgument::from_value(LargeArgument { words: [1, 2, 3] });
504        assert!(matches!(argument, OwnedKernelArgument::Boxed(_)));
505
506        let expected = match &mut argument {
507            OwnedKernelArgument::Boxed(value) => value.as_mut().as_mut_ptr(),
508            OwnedKernelArgument::Inline(_) => unreachable!(),
509        };
510
511        assert_eq!(argument.as_mut_ptr(), expected);
512    }
513}