oxicuda-launch 0.1.2

OxiCUDA Launch - Type-safe GPU kernel launch infrastructure
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
//! Type-safe GPU kernel management and argument passing.
//!
//! This module provides the [`Kernel`] struct for launching GPU kernels
//! and the [`KernelArgs`] trait for type-safe argument passing to CUDA
//! kernel functions.
//!
//! # Architecture
//!
//! A [`Kernel`] wraps a [`Function`] handle and holds an `Arc<Module>`
//! to ensure the PTX module remains loaded for the kernel's lifetime.
//! Arguments are passed via the [`KernelArgs`] trait, which converts
//! typed Rust values into the `*mut c_void` array that `cuLaunchKernel`
//! expects.
//!
//! # Tuple arguments
//!
//! The [`KernelArgs`] trait is implemented for tuples of `Copy` types
//! up to 24 elements. Each element must be `Copy` because kernel
//! arguments are passed by value to the GPU.
//!
//! # Example
//!
//! ```rust,no_run
//! # use std::sync::Arc;
//! # use oxicuda_driver::{Module, Stream, Context, Device};
//! # use oxicuda_launch::{Kernel, LaunchParams, Dim3};
//! # fn main() -> oxicuda_driver::CudaResult<()> {
//! # oxicuda_driver::init()?;
//! # let dev = Device::get(0)?;
//! # let ctx = Arc::new(Context::new(&dev)?);
//! # let ptx = "";
//! let module = Arc::new(Module::from_ptx(ptx)?);
//! let kernel = Kernel::from_module(module, "vector_add")?;
//!
//! let stream = Stream::new(&ctx)?;
//! let params = LaunchParams::new(4u32, 256u32);
//!
//! // Launch with typed arguments: (a_ptr, b_ptr, c_ptr, n)
//! let args = (0u64, 0u64, 0u64, 1024u32);
//! kernel.launch(&params, &stream, &args)?;
//! # Ok(())
//! # }
//! ```

use std::ffi::c_void;
use std::sync::Arc;

use oxicuda_driver::error::CudaResult;
use oxicuda_driver::loader::try_driver;
use oxicuda_driver::module::{Function, Module};
use oxicuda_driver::stream::Stream;

use crate::params::LaunchParams;
use crate::trace::KernelSpanGuard;

// ---------------------------------------------------------------------------
// KernelArgs trait
// ---------------------------------------------------------------------------

/// Trait for types that can be passed as kernel arguments.
///
/// Kernel arguments must be convertible to an array of void pointers
/// that `cuLaunchKernel` accepts. Each pointer points to the argument
/// value on the host; the CUDA driver copies the values to the GPU
/// before the kernel executes.
///
/// # Safety
///
/// Implementors must ensure that:
/// - `as_param_ptrs` returns valid pointers to the argument values.
/// - The pointed-to values remain valid for the duration of the kernel launch
///   (i.e., until `cuLaunchKernel` returns).
/// - The argument types and sizes match what the kernel expects.
pub unsafe trait KernelArgs {
    /// Convert arguments to an array of void pointers for `cuLaunchKernel`.
    ///
    /// Each element in the returned `Vec` is a pointer to one kernel argument.
    /// The CUDA driver reads the value through each pointer and copies it
    /// to the GPU.
    fn as_param_ptrs(&self) -> Vec<*mut c_void>;
}

// ---------------------------------------------------------------------------
// KernelArgs — unit type (no arguments)
// ---------------------------------------------------------------------------

/// Implementation for kernels that take no arguments.
///
/// # Safety
///
/// Returns an empty pointer array, which is valid for zero-argument kernels.
unsafe impl KernelArgs for () {
    #[inline]
    fn as_param_ptrs(&self) -> Vec<*mut c_void> {
        Vec::new()
    }
}

// ---------------------------------------------------------------------------
// KernelArgs — tuple implementations via macro
// ---------------------------------------------------------------------------

/// Generates [`KernelArgs`] implementations for tuples of `Copy` types.
///
/// Each tuple element is converted to a `*mut c_void` by taking
/// a reference to the element and casting through `*const T`.
macro_rules! impl_kernel_args_tuple {
    ($($idx:tt: $T:ident),+) => {
        /// # Safety
        ///
        /// The pointers returned point into `self`, which must remain
        /// valid (i.e., not moved or dropped) until `cuLaunchKernel` returns.
        unsafe impl<$($T: Copy),+> KernelArgs for ($($T,)+) {
            #[inline]
            fn as_param_ptrs(&self) -> Vec<*mut c_void> {
                vec![
                    $(&self.$idx as *const $T as *mut c_void,)+
                ]
            }
        }
    };
}

impl_kernel_args_tuple!(0: A);
impl_kernel_args_tuple!(0: A, 1: B);
impl_kernel_args_tuple!(0: A, 1: B, 2: C);
impl_kernel_args_tuple!(0: A, 1: B, 2: C, 3: D);
impl_kernel_args_tuple!(0: A, 1: B, 2: C, 3: D, 4: E);
impl_kernel_args_tuple!(0: A, 1: B, 2: C, 3: D, 4: E, 5: F);
impl_kernel_args_tuple!(0: A, 1: B, 2: C, 3: D, 4: E, 5: F, 6: G);
impl_kernel_args_tuple!(0: A, 1: B, 2: C, 3: D, 4: E, 5: F, 6: G, 7: H);
impl_kernel_args_tuple!(0: A, 1: B, 2: C, 3: D, 4: E, 5: F, 6: G, 7: H, 8: I);
impl_kernel_args_tuple!(0: A, 1: B, 2: C, 3: D, 4: E, 5: F, 6: G, 7: H, 8: I, 9: J);
impl_kernel_args_tuple!(0: A, 1: B, 2: C, 3: D, 4: E, 5: F, 6: G, 7: H, 8: I, 9: J, 10: K);
impl_kernel_args_tuple!(0: A, 1: B, 2: C, 3: D, 4: E, 5: F, 6: G, 7: H, 8: I, 9: J, 10: K, 11: L);
impl_kernel_args_tuple!(0: A, 1: B, 2: C, 3: D, 4: E, 5: F, 6: G, 7: H, 8: I, 9: J, 10: K, 11: L, 12: M);
impl_kernel_args_tuple!(0: A, 1: B, 2: C, 3: D, 4: E, 5: F, 6: G, 7: H, 8: I, 9: J, 10: K, 11: L, 12: M, 13: N);
impl_kernel_args_tuple!(0: A, 1: B, 2: C, 3: D, 4: E, 5: F, 6: G, 7: H, 8: I, 9: J, 10: K, 11: L, 12: M, 13: N, 14: O);
impl_kernel_args_tuple!(0: A, 1: B, 2: C, 3: D, 4: E, 5: F, 6: G, 7: H, 8: I, 9: J, 10: K, 11: L, 12: M, 13: N, 14: O, 15: P);
impl_kernel_args_tuple!(0: A, 1: B, 2: C, 3: D, 4: E, 5: F, 6: G, 7: H, 8: I, 9: J, 10: K, 11: L, 12: M, 13: N, 14: O, 15: P, 16: Q);
impl_kernel_args_tuple!(0: A, 1: B, 2: C, 3: D, 4: E, 5: F, 6: G, 7: H, 8: I, 9: J, 10: K, 11: L, 12: M, 13: N, 14: O, 15: P, 16: Q, 17: R);
impl_kernel_args_tuple!(0: A, 1: B, 2: C, 3: D, 4: E, 5: F, 6: G, 7: H, 8: I, 9: J, 10: K, 11: L, 12: M, 13: N, 14: O, 15: P, 16: Q, 17: R, 18: S);
impl_kernel_args_tuple!(0: A, 1: B, 2: C, 3: D, 4: E, 5: F, 6: G, 7: H, 8: I, 9: J, 10: K, 11: L, 12: M, 13: N, 14: O, 15: P, 16: Q, 17: R, 18: S, 19: T);
impl_kernel_args_tuple!(0: A, 1: B, 2: C, 3: D, 4: E, 5: F, 6: G, 7: H, 8: I, 9: J, 10: K, 11: L, 12: M, 13: N, 14: O, 15: P, 16: Q, 17: R, 18: S, 19: T, 20: U);
impl_kernel_args_tuple!(0: A, 1: B, 2: C, 3: D, 4: E, 5: F, 6: G, 7: H, 8: I, 9: J, 10: K, 11: L, 12: M, 13: N, 14: O, 15: P, 16: Q, 17: R, 18: S, 19: T, 20: U, 21: V);
impl_kernel_args_tuple!(0: A, 1: B, 2: C, 3: D, 4: E, 5: F, 6: G, 7: H, 8: I, 9: J, 10: K, 11: L, 12: M, 13: N, 14: O, 15: P, 16: Q, 17: R, 18: S, 19: T, 20: U, 21: V, 22: W);
impl_kernel_args_tuple!(0: A, 1: B, 2: C, 3: D, 4: E, 5: F, 6: G, 7: H, 8: I, 9: J, 10: K, 11: L, 12: M, 13: N, 14: O, 15: P, 16: Q, 17: R, 18: S, 19: T, 20: U, 21: V, 22: W, 23: X);

// ---------------------------------------------------------------------------
// Kernel struct
// ---------------------------------------------------------------------------

/// A launchable GPU kernel with module lifetime management.
///
/// Holds an `Arc<Module>` to ensure the PTX module remains loaded
/// as long as any `Kernel` references it. This is important because
/// [`Function`] handles become invalid once their parent module is
/// unloaded.
///
/// # Creating a kernel
///
/// ```rust,no_run
/// # use std::sync::Arc;
/// # use oxicuda_driver::Module;
/// # use oxicuda_launch::Kernel;
/// # fn main() -> oxicuda_driver::CudaResult<()> {
/// # let ptx = "";
/// let module = Arc::new(Module::from_ptx(ptx)?);
/// let kernel = Kernel::from_module(module, "my_kernel")?;
/// println!("loaded kernel: {}", kernel.name());
/// # Ok(())
/// # }
/// ```
///
/// # Launching
///
/// ```rust,no_run
/// # use std::sync::Arc;
/// # use oxicuda_driver::{Module, Stream, Context, Device};
/// # use oxicuda_launch::{Kernel, LaunchParams};
/// # fn main() -> oxicuda_driver::CudaResult<()> {
/// # oxicuda_driver::init()?;
/// # let dev = Device::get(0)?;
/// # let ctx = Arc::new(Context::new(&dev)?);
/// # let ptx = "";
/// # let module = Arc::new(Module::from_ptx(ptx)?);
/// # let kernel = Kernel::from_module(module, "my_kernel")?;
/// let stream = Stream::new(&ctx)?;
/// let params = LaunchParams::new(4u32, 256u32);
/// kernel.launch(&params, &stream, &(42u32, 1024u32))?;
/// # Ok(())
/// # }
/// ```
pub struct Kernel {
    /// The underlying CUDA function handle.
    function: Function,
    /// Keeps the parent module alive as long as this kernel exists.
    _module: Arc<Module>,
    /// The kernel function name (for debugging and diagnostics).
    name: String,
}

impl Kernel {
    /// Creates a new `Kernel` from a module and function name.
    ///
    /// Looks up the named function in the module. The `Arc<Module>` ensures
    /// the module is not unloaded while this kernel exists.
    ///
    /// # Errors
    ///
    /// Returns [`CudaError::NotFound`](oxicuda_driver::CudaError::NotFound) if no
    /// function with the given name exists in the module, or another
    /// [`CudaError`](oxicuda_driver::CudaError) on driver failure.
    pub fn from_module(module: Arc<Module>, name: &str) -> CudaResult<Self> {
        let function = module.get_function(name)?;
        Ok(Self {
            function,
            _module: module,
            name: name.to_owned(),
        })
    }

    /// Launches the kernel with the given parameters and arguments on a stream.
    ///
    /// This is the primary entry point for kernel execution. It calls
    /// `cuLaunchKernel` with the specified grid/block dimensions, shared
    /// memory, stream, and kernel arguments.
    ///
    /// The launch is asynchronous — it returns immediately and the kernel
    /// executes on the GPU. Use [`Stream::synchronize`] to wait for completion.
    ///
    /// # Type safety
    ///
    /// The `args` parameter accepts any type implementing [`KernelArgs`],
    /// including tuples of `Copy` types up to 24 elements. The caller is
    /// responsible for ensuring the argument types match the kernel signature.
    ///
    /// # Errors
    ///
    /// Returns a [`CudaError`](oxicuda_driver::CudaError) if the launch fails
    /// (e.g., invalid dimensions, insufficient resources, driver error).
    pub fn launch<A: KernelArgs>(
        &self,
        params: &LaunchParams,
        stream: &Stream,
        args: &A,
    ) -> CudaResult<()> {
        // Emit a tracing span for this kernel launch (no-op when the
        // `tracing` feature is disabled).
        let _span = KernelSpanGuard::enter(
            &self.name,
            (params.grid.x, params.grid.y, params.grid.z),
            (params.block.x, params.block.y, params.block.z),
        );

        let driver = try_driver()?;
        let mut param_ptrs = args.as_param_ptrs();
        oxicuda_driver::error::check(unsafe {
            (driver.cu_launch_kernel)(
                self.function.raw(),
                params.grid.x,
                params.grid.y,
                params.grid.z,
                params.block.x,
                params.block.y,
                params.block.z,
                params.shared_mem_bytes,
                stream.raw(),
                param_ptrs.as_mut_ptr(),
                std::ptr::null_mut(),
            )
        })
    }

    /// Returns the kernel function name.
    #[inline]
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Returns a reference to the underlying [`Function`] handle.
    ///
    /// This can be used for occupancy queries and other function-level
    /// operations provided by `oxicuda-driver`.
    #[inline]
    pub fn function(&self) -> &Function {
        &self.function
    }

    /// Returns the maximum number of active blocks per streaming multiprocessor
    /// for a given block size and dynamic shared memory.
    ///
    /// Delegates to [`Function::max_active_blocks_per_sm`].
    ///
    /// # Parameters
    ///
    /// * `block_size` — number of threads per block.
    /// * `dynamic_smem` — dynamic shared memory per block in bytes.
    ///
    /// # Errors
    ///
    /// Returns a [`CudaError`](oxicuda_driver::CudaError) if the query fails.
    pub fn max_active_blocks_per_sm(
        &self,
        block_size: i32,
        dynamic_smem: usize,
    ) -> CudaResult<i32> {
        self.function
            .max_active_blocks_per_sm(block_size, dynamic_smem)
    }

    /// Returns the optimal block size for this kernel and the minimum
    /// grid size to achieve maximum occupancy.
    ///
    /// Delegates to [`Function::optimal_block_size`].
    ///
    /// Returns `(min_grid_size, optimal_block_size)`.
    ///
    /// # Parameters
    ///
    /// * `dynamic_smem` — dynamic shared memory per block in bytes.
    ///
    /// # Errors
    ///
    /// Returns a [`CudaError`](oxicuda_driver::CudaError) if the query fails.
    pub fn optimal_block_size(&self, dynamic_smem: usize) -> CudaResult<(i32, i32)> {
        self.function.optimal_block_size(dynamic_smem)
    }
}

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

impl std::fmt::Display for Kernel {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Kernel({})", self.name)
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    #[test]
    fn unit_args_empty() {
        let args = ();
        let ptrs = args.as_param_ptrs();
        assert!(ptrs.is_empty());
    }

    #[test]
    fn single_arg_ptr_valid() {
        let args = (42u32,);
        let ptrs = args.as_param_ptrs();
        assert_eq!(ptrs.len(), 1);
        // Verify the pointer actually points to the value.
        let val_ptr = ptrs[0] as *const u32;
        assert_eq!(unsafe { *val_ptr }, 42u32);
    }

    #[test]
    fn two_args_ptr_valid() {
        let args = (10u32, 20u64);
        let ptrs = args.as_param_ptrs();
        assert_eq!(ptrs.len(), 2);
        assert_eq!(unsafe { *(ptrs[0] as *const u32) }, 10u32);
        assert_eq!(unsafe { *(ptrs[1] as *const u64) }, 20u64);
    }

    #[test]
    fn four_args_ptr_valid() {
        let args = (1u32, 2u64, 3.0f32, 4.0f64);
        let ptrs = args.as_param_ptrs();
        assert_eq!(ptrs.len(), 4);
        assert_eq!(unsafe { *(ptrs[0] as *const u32) }, 1u32);
        assert_eq!(unsafe { *(ptrs[1] as *const u64) }, 2u64);
        assert!((unsafe { *(ptrs[2] as *const f32) } - 3.0f32).abs() < f32::EPSILON);
        assert!((unsafe { *(ptrs[3] as *const f64) } - 4.0f64).abs() < f64::EPSILON);
    }

    #[test]
    fn twelve_args_count() {
        let args = (
            1u32, 2u32, 3u32, 4u32, 5u32, 6u32, 7u32, 8u32, 9u32, 10u32, 11u32, 12u32,
        );
        let ptrs = args.as_param_ptrs();
        assert_eq!(ptrs.len(), 12);
        for (i, ptr) in ptrs.iter().enumerate() {
            let val = unsafe { *(*ptr as *const u32) };
            assert_eq!(val, (i as u32) + 1);
        }
    }

    // ---------------------------------------------------------------------------
    // Quality gate tests (CPU-only, E2E PTX chain parameter verification)
    // ---------------------------------------------------------------------------

    #[test]
    fn launch_params_grid_calculation_e2e() {
        // Given n = 1_048_576 (1M elements) and block_size = 256,
        // grid_size_for must return exactly 4096 (ceiling division).
        let n: u32 = 1_048_576;
        let block_size: u32 = 256;
        let grid = crate::grid::grid_size_for(n, block_size);
        assert_eq!(
            grid, 4096,
            "grid_size_for(1M, 256) must be 4096, got {grid}"
        );
        // Also verify via arithmetic: 1_048_576 / 256 == 4096 exactly
        assert_eq!(
            n % block_size,
            0,
            "n must be exactly divisible by block_size"
        );
    }

    #[test]
    fn launch_params_stores_grid_and_block() {
        // LaunchParams::new(4096, 256) must record grid==4096 and block==256.
        let params = LaunchParams::new(4096u32, 256u32);
        assert_eq!(
            params.grid.x, 4096,
            "grid.x must be 4096, got {}",
            params.grid.x
        );
        assert_eq!(
            params.block.x, 256,
            "block.x must be 256, got {}",
            params.block.x
        );
        assert_eq!(params.shared_mem_bytes, 0);
        // Total threads: 4096 * 256 = 1_048_576
        assert_eq!(params.total_threads(), 1_048_576);
    }

    #[test]
    fn named_args_builder_chain() {
        // ArgBuilder::new().add("a", &1u32).add("b", &2.0f32).build() must have length 2.
        use crate::named_args::ArgBuilder;
        let a: u32 = 1;
        let b: f32 = 2.0;
        let mut builder = ArgBuilder::new();
        builder.add("a", &a).add("b", &b);
        assert_eq!(
            builder.arg_count(),
            2,
            "ArgBuilder with 2 pushes must have length 2"
        );
        let ptrs = builder.build();
        assert_eq!(ptrs.len(), 2, "build() must return 2 pointers");
    }
}