Skip to main content

singe_cuda/module/
config.rs

1use std::{ffi, ptr};
2
3use singe_cuda_sys::driver;
4
5use crate::{
6    dim::Dim3,
7    error::{Error, Result},
8    try_ffi,
9    types::{ClusterSchedulingPolicy, SharedMemoryMode},
10    utility::{to_u32, to_u64, to_usize},
11};
12
13/// Grid, block and dynamic shared-memory dimensions, independent of launch attributes.
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub struct LaunchGeometry {
16    grid_dim: Dim3,
17    block_dim: Dim3,
18    shared_memory_bytes: usize,
19}
20
21/// Launch geometry and attributes used when submitting or constructing a kernel node.
22#[derive(Debug, Clone)]
23pub struct LaunchConfig {
24    geometry: LaunchGeometry,
25    attributes: Vec<LaunchAttribute>,
26}
27
28impl LaunchGeometry {
29    /// Creates nonzero grid and block dimensions with a representable shared-memory byte count.
30    ///
31    /// Device and kernel limits are checked during preparation or by CUDA during submission.
32    ///
33    /// # Errors
34    ///
35    /// Returns an error for zero dimensions or a shared-memory byte count exceeding `u32::MAX`.
36    pub fn create(grid_dim: Dim3, block_dim: Dim3, shared_memory_bytes: usize) -> Result<Self> {
37        validate_dim3(grid_dim, "grid_dim")?;
38        validate_dim3(block_dim, "block_dim")?;
39        validate_shared_memory_bytes(shared_memory_bytes)?;
40        Ok(Self::from_validated(
41            grid_dim,
42            block_dim,
43            shared_memory_bytes,
44        ))
45    }
46
47    const fn from_validated(grid_dim: Dim3, block_dim: Dim3, shared_memory_bytes: usize) -> Self {
48        Self {
49            grid_dim,
50            block_dim,
51            shared_memory_bytes,
52        }
53    }
54
55    /// Returns the number of blocks along each grid axis.
56    #[must_use]
57    pub const fn grid_dim(&self) -> Dim3 {
58        self.grid_dim
59    }
60
61    /// Returns the number of threads along each block axis.
62    #[must_use]
63    pub const fn block_dim(&self) -> Dim3 {
64        self.block_dim
65    }
66
67    /// Returns the dynamic shared-memory bytes per block.
68    #[must_use]
69    pub const fn shared_memory_bytes(&self) -> usize {
70        self.shared_memory_bytes
71    }
72
73    pub(crate) fn shared_memory_bytes_u32(&self) -> u32 {
74        u32::try_from(self.shared_memory_bytes)
75            .expect("shared memory byte count is validated on construction")
76    }
77
78    /// Replaces the dynamic shared-memory byte count.
79    ///
80    /// # Errors
81    ///
82    /// Returns an error if the byte count exceeds `u32::MAX`.
83    pub fn with_shared_memory_bytes(mut self, shared_memory_bytes: usize) -> Result<Self> {
84        validate_shared_memory_bytes(shared_memory_bytes)?;
85        self.shared_memory_bytes = shared_memory_bytes;
86        Ok(self)
87    }
88
89    /// Creates a one-dimensional launch covering `element_count` elements with `block_size` threads per block.
90    ///
91    /// Each grid axis rounds up to a whole block.
92    /// Dynamic shared memory starts at zero.
93    /// Device and kernel limits are checked during preparation or submission.
94    ///
95    /// # Errors
96    ///
97    /// Returns `Error::NotPositive` if an element extent or block dimension is zero, or `Error::OutOfRange` if a computed grid dimension or supplied block dimension exceeds `u32::MAX`.
98    pub fn try_for_1d_grid(element_count: usize, block_size: usize) -> Result<Self> {
99        validate_block_dimension(block_size, "block_size")?;
100        let grid_size = element_count.div_ceil(block_size);
101
102        validate_grid_dimension(grid_size, "grid_size")?;
103
104        Ok(Self::from_validated(
105            Dim3::new(to_u32(grid_size, "grid_size")?, 1, 1),
106            Dim3::new(to_u32(block_size, "block_size")?, 1, 1),
107            0,
108        ))
109    }
110
111    /// Creates a one-dimensional launch covering `element_count` elements with `block_size` threads per block.
112    ///
113    /// Uses the same rounding, shared-memory defaults, and validation as [`Self::try_for_1d_grid`].
114    ///
115    /// # Panics
116    ///
117    /// Panics if an element extent or block dimension is zero, or if a computed grid dimension or supplied block dimension exceeds `u32::MAX`.
118    /// Use [`Self::try_for_1d_grid`] to handle these errors.
119    #[must_use]
120    pub fn for_1d_grid(element_count: usize, block_size: usize) -> Self {
121        Self::try_for_1d_grid(element_count, block_size)
122            .expect("invalid 1d cuda launch configuration")
123    }
124
125    /// Creates a one-dimensional launch covering `element_count` elements with `block_size` threads per block.
126    /// Equivalent to [`Self::try_for_1d_grid`].
127    ///
128    /// Each grid axis rounds up to a whole block.
129    /// Dynamic shared memory starts at zero.
130    /// Device and kernel limits are checked during preparation or submission.
131    ///
132    /// # Errors
133    ///
134    /// Returns `Error::NotPositive` if an element extent or block dimension is zero, or `Error::OutOfRange` if a computed grid dimension or supplied block dimension exceeds `u32::MAX`.
135    pub fn try_for_num_elems(element_count: usize, block_size: usize) -> Result<Self> {
136        Self::try_for_1d_grid(element_count, block_size)
137    }
138
139    /// Creates a one-dimensional launch covering `element_count` elements with `block_size` threads per block.
140    /// Equivalent to [`Self::try_for_1d_grid`].
141    ///
142    /// Uses the same rounding, shared-memory defaults, and validation as [`Self::try_for_num_elems`].
143    ///
144    /// # Panics
145    ///
146    /// Panics if an element extent or block dimension is zero, or if a computed grid dimension or supplied block dimension exceeds `u32::MAX`.
147    /// Use [`Self::try_for_num_elems`] to handle these errors.
148    #[must_use]
149    pub fn for_num_elems(element_count: usize, block_size: usize) -> Self {
150        Self::try_for_num_elems(element_count, block_size)
151            .expect("invalid cuda launch configuration")
152    }
153
154    /// Creates a two-dimensional launch covering `width` by `height` elements with the supplied block width and height.
155    ///
156    /// Each grid axis rounds up to a whole block.
157    /// Dynamic shared memory starts at zero.
158    /// Device and kernel limits are checked during preparation or submission.
159    ///
160    /// # Errors
161    ///
162    /// Returns `Error::NotPositive` if an element extent or block dimension is zero, or `Error::OutOfRange` if a computed grid dimension or supplied block dimension exceeds `u32::MAX`.
163    pub fn try_for_2d_grid(
164        width: usize,
165        height: usize,
166        block_width: usize,
167        block_height: usize,
168    ) -> Result<Self> {
169        validate_block_dimension(block_width, "block_width")?;
170        validate_block_dimension(block_height, "block_height")?;
171        let grid_x = width.div_ceil(block_width);
172        let grid_y = height.div_ceil(block_height);
173        validate_grid_dimension(grid_x, "grid_x")?;
174        validate_grid_dimension(grid_y, "grid_y")?;
175
176        Ok(Self::from_validated(
177            Dim3::new(to_u32(grid_x, "grid_x")?, to_u32(grid_y, "grid_y")?, 1),
178            Dim3::new(
179                to_u32(block_width, "block_width")?,
180                to_u32(block_height, "block_height")?,
181                1,
182            ),
183            0,
184        ))
185    }
186
187    /// Creates a two-dimensional launch covering `width` by `height` elements with the supplied block width and height.
188    ///
189    /// Uses the same rounding, shared-memory defaults, and validation as [`Self::try_for_2d_grid`].
190    ///
191    /// # Panics
192    ///
193    /// Panics if an element extent or block dimension is zero, or if a computed grid dimension or supplied block dimension exceeds `u32::MAX`.
194    /// Use [`Self::try_for_2d_grid`] to handle these errors.
195    #[must_use]
196    pub fn for_2d_grid(
197        width: usize,
198        height: usize,
199        block_width: usize,
200        block_height: usize,
201    ) -> Self {
202        Self::try_for_2d_grid(width, height, block_width, block_height)
203            .expect("invalid 2d cuda launch configuration")
204    }
205
206    /// Creates a three-dimensional launch covering `width` by `height` by `depth` elements with the supplied block dimensions.
207    ///
208    /// Each grid axis rounds up to a whole block.
209    /// Dynamic shared memory starts at zero.
210    /// Device and kernel limits are checked during preparation or submission.
211    ///
212    /// # Errors
213    ///
214    /// Returns `Error::NotPositive` if an element extent or block dimension is zero, or `Error::OutOfRange` if a computed grid dimension or supplied block dimension exceeds `u32::MAX`.
215    pub fn try_for_3d_grid(
216        width: usize,
217        height: usize,
218        depth: usize,
219        block_width: usize,
220        block_height: usize,
221        block_depth: usize,
222    ) -> Result<Self> {
223        validate_block_dimension(block_width, "block_width")?;
224        validate_block_dimension(block_height, "block_height")?;
225        validate_block_dimension(block_depth, "block_depth")?;
226        let grid_x = width.div_ceil(block_width);
227        let grid_y = height.div_ceil(block_height);
228        let grid_z = depth.div_ceil(block_depth);
229        validate_grid_dimension(grid_x, "grid_x")?;
230        validate_grid_dimension(grid_y, "grid_y")?;
231        validate_grid_dimension(grid_z, "grid_z")?;
232
233        Ok(Self::from_validated(
234            Dim3::new(
235                to_u32(grid_x, "grid_x")?,
236                to_u32(grid_y, "grid_y")?,
237                to_u32(grid_z, "grid_z")?,
238            ),
239            Dim3::new(
240                to_u32(block_width, "block_width")?,
241                to_u32(block_height, "block_height")?,
242                to_u32(block_depth, "block_depth")?,
243            ),
244            0,
245        ))
246    }
247
248    /// Creates a three-dimensional launch covering `width` by `height` by `depth` elements with the supplied block dimensions.
249    ///
250    /// Uses the same rounding, shared-memory defaults, and validation as [`Self::try_for_3d_grid`].
251    ///
252    /// # Panics
253    ///
254    /// Panics if an element extent or block dimension is zero, or if a computed grid dimension or supplied block dimension exceeds `u32::MAX`.
255    /// Use [`Self::try_for_3d_grid`] to handle these errors.
256    #[must_use]
257    pub fn for_3d_grid(
258        width: usize,
259        height: usize,
260        depth: usize,
261        block_width: usize,
262        block_height: usize,
263        block_depth: usize,
264    ) -> Self {
265        Self::try_for_3d_grid(width, height, depth, block_width, block_height, block_depth)
266            .expect("invalid 3d cuda launch configuration")
267    }
268}
269
270impl LaunchConfig {
271    /// Creates a launch configuration with the supplied grid dimensions, block dimensions, and dynamic shared-memory bytes per block.
272    ///
273    /// No launch attributes are set.
274    /// Device and kernel limits are checked during preparation or submission.
275    ///
276    /// # Errors
277    ///
278    /// Returns `Error::NotPositive` if any grid or block axis is zero, or `Error::OutOfRange` if `shared_memory_bytes` exceeds `u32::MAX`.
279    pub fn create(grid_dim: Dim3, block_dim: Dim3, shared_memory_bytes: usize) -> Result<Self> {
280        Ok(LaunchGeometry::create(grid_dim, block_dim, shared_memory_bytes)?.into())
281    }
282
283    /// Returns the geometry used by this launch, without its attributes.
284    #[must_use]
285    pub const fn geometry(&self) -> &LaunchGeometry {
286        &self.geometry
287    }
288
289    /// Returns the number of blocks along each grid axis.
290    #[must_use]
291    pub const fn grid_dim(&self) -> Dim3 {
292        self.geometry.grid_dim()
293    }
294
295    /// Returns the number of threads along each block axis.
296    #[must_use]
297    pub const fn block_dim(&self) -> Dim3 {
298        self.geometry.block_dim()
299    }
300
301    /// Returns the dynamic shared-memory bytes per block.
302    #[must_use]
303    pub const fn shared_memory_bytes(&self) -> usize {
304        self.geometry.shared_memory_bytes()
305    }
306
307    pub(crate) fn shared_memory_bytes_u32(&self) -> u32 {
308        self.geometry.shared_memory_bytes_u32()
309    }
310
311    /// Replaces the dynamic shared-memory byte count per block.
312    ///
313    /// # Errors
314    ///
315    /// Returns `Error::OutOfRange` if `bytes` exceeds `u32::MAX`.
316    pub fn with_shared_memory_bytes(mut self, bytes: usize) -> Result<Self> {
317        self.geometry = self.geometry.with_shared_memory_bytes(bytes)?;
318        Ok(self)
319    }
320
321    /// Creates a one-dimensional launch covering `element_count` elements with `block_size` threads per block.
322    ///
323    /// Each grid axis rounds up to a whole block.
324    /// Dynamic shared memory starts at zero.
325    /// The configuration starts with no launch attributes.
326    /// Device and kernel limits are checked during preparation or submission.
327    ///
328    /// # Errors
329    ///
330    /// Returns `Error::NotPositive` if an element extent or block dimension is zero, or `Error::OutOfRange` if a computed grid dimension or supplied block dimension exceeds `u32::MAX`.
331    pub fn try_for_1d_grid(element_count: usize, block_size: usize) -> Result<Self> {
332        Ok(LaunchGeometry::try_for_1d_grid(element_count, block_size)?.into())
333    }
334
335    /// Creates a one-dimensional launch covering `element_count` elements with `block_size` threads per block.
336    ///
337    /// Uses the same rounding, shared-memory defaults, and validation as [`Self::try_for_1d_grid`].
338    ///
339    /// # Panics
340    ///
341    /// Panics if an element extent or block dimension is zero, or if a computed grid dimension or supplied block dimension exceeds `u32::MAX`.
342    /// Use [`Self::try_for_1d_grid`] to handle these errors.
343    #[must_use]
344    pub fn for_1d_grid(element_count: usize, block_size: usize) -> Self {
345        LaunchGeometry::for_1d_grid(element_count, block_size).into()
346    }
347
348    /// Creates a one-dimensional launch covering `element_count` elements with `block_size` threads per block.
349    /// Equivalent to [`Self::try_for_1d_grid`].
350    ///
351    /// Each grid axis rounds up to a whole block.
352    /// Dynamic shared memory starts at zero.
353    /// The configuration starts with no launch attributes.
354    /// Device and kernel limits are checked during preparation or submission.
355    ///
356    /// # Errors
357    ///
358    /// Returns `Error::NotPositive` if an element extent or block dimension is zero, or `Error::OutOfRange` if a computed grid dimension or supplied block dimension exceeds `u32::MAX`.
359    pub fn try_for_num_elems(element_count: usize, block_size: usize) -> Result<Self> {
360        Ok(LaunchGeometry::try_for_num_elems(element_count, block_size)?.into())
361    }
362
363    /// Creates a one-dimensional launch covering `element_count` elements with `block_size` threads per block.
364    /// Equivalent to [`Self::try_for_1d_grid`].
365    ///
366    /// Uses the same rounding, shared-memory defaults, and validation as [`Self::try_for_num_elems`].
367    ///
368    /// # Panics
369    ///
370    /// Panics if an element extent or block dimension is zero, or if a computed grid dimension or supplied block dimension exceeds `u32::MAX`.
371    /// Use [`Self::try_for_num_elems`] to handle these errors.
372    #[must_use]
373    pub fn for_num_elems(element_count: usize, block_size: usize) -> Self {
374        LaunchGeometry::for_num_elems(element_count, block_size).into()
375    }
376
377    /// Creates a two-dimensional launch covering `width` by `height` elements with the supplied block width and height.
378    ///
379    /// Each grid axis rounds up to a whole block.
380    /// Dynamic shared memory starts at zero.
381    /// The configuration starts with no launch attributes.
382    /// Device and kernel limits are checked during preparation or submission.
383    ///
384    /// # Errors
385    ///
386    /// Returns `Error::NotPositive` if an element extent or block dimension is zero, or `Error::OutOfRange` if a computed grid dimension or supplied block dimension exceeds `u32::MAX`.
387    pub fn try_for_2d_grid(
388        width: usize,
389        height: usize,
390        block_width: usize,
391        block_height: usize,
392    ) -> Result<Self> {
393        Ok(LaunchGeometry::try_for_2d_grid(width, height, block_width, block_height)?.into())
394    }
395
396    /// Creates a two-dimensional launch covering `width` by `height` elements with the supplied block width and height.
397    ///
398    /// Uses the same rounding, shared-memory defaults, and validation as [`Self::try_for_2d_grid`].
399    ///
400    /// # Panics
401    ///
402    /// Panics if an element extent or block dimension is zero, or if a computed grid dimension or supplied block dimension exceeds `u32::MAX`.
403    /// Use [`Self::try_for_2d_grid`] to handle these errors.
404    #[must_use]
405    pub fn for_2d_grid(
406        width: usize,
407        height: usize,
408        block_width: usize,
409        block_height: usize,
410    ) -> Self {
411        LaunchGeometry::for_2d_grid(width, height, block_width, block_height).into()
412    }
413
414    /// Creates a three-dimensional launch covering `width` by `height` by `depth` elements with the supplied block dimensions.
415    ///
416    /// Each grid axis rounds up to a whole block.
417    /// Dynamic shared memory starts at zero.
418    /// The configuration starts with no launch attributes.
419    /// Device and kernel limits are checked during preparation or submission.
420    ///
421    /// # Errors
422    ///
423    /// Returns `Error::NotPositive` if an element extent or block dimension is zero, or `Error::OutOfRange` if a computed grid dimension or supplied block dimension exceeds `u32::MAX`.
424    pub fn try_for_3d_grid(
425        width: usize,
426        height: usize,
427        depth: usize,
428        block_width: usize,
429        block_height: usize,
430        block_depth: usize,
431    ) -> Result<Self> {
432        Ok(LaunchGeometry::try_for_3d_grid(
433            width,
434            height,
435            depth,
436            block_width,
437            block_height,
438            block_depth,
439        )?
440        .into())
441    }
442
443    /// Creates a three-dimensional launch covering `width` by `height` by `depth` elements with the supplied block dimensions.
444    ///
445    /// Uses the same rounding, shared-memory defaults, and validation as [`Self::try_for_3d_grid`].
446    ///
447    /// # Panics
448    ///
449    /// Panics if an element extent or block dimension is zero, or if a computed grid dimension or supplied block dimension exceeds `u32::MAX`.
450    /// Use [`Self::try_for_3d_grid`] to handle these errors.
451    #[must_use]
452    pub fn for_3d_grid(
453        width: usize,
454        height: usize,
455        depth: usize,
456        block_width: usize,
457        block_height: usize,
458        block_depth: usize,
459    ) -> Self {
460        LaunchGeometry::for_3d_grid(width, height, depth, block_width, block_height, block_depth)
461            .into()
462    }
463}
464
465impl From<LaunchGeometry> for LaunchConfig {
466    fn from(geometry: LaunchGeometry) -> Self {
467        Self {
468            geometry,
469            attributes: Vec::new(),
470        }
471    }
472}
473
474fn validate_dim3(value: Dim3, name: &str) -> Result<()> {
475    validate_grid_dimension(to_usize(value.x, "grid dimension")?, &format!("{name}.x"))?;
476    validate_grid_dimension(to_usize(value.y, "grid dimension")?, &format!("{name}.y"))?;
477    validate_grid_dimension(to_usize(value.z, "grid dimension")?, &format!("{name}.z"))?;
478    Ok(())
479}
480
481fn validate_grid_dimension(value: usize, name: &str) -> Result<()> {
482    if value == 0 {
483        return Err(Error::not_positive(name.to_owned()));
484    }
485    Ok(())
486}
487
488fn validate_block_dimension(value: usize, name: &str) -> Result<()> {
489    if value == 0 {
490        return Err(Error::not_positive(name.to_owned()));
491    }
492    Ok(())
493}
494
495fn validate_shared_memory_bytes(value: usize) -> Result<u32> {
496    to_u32(value, "shared_memory_bytes")
497}
498
499pub(crate) fn validate_dynamic_shared_memory_bytes(value: usize) -> Result<u64> {
500    to_u64(value, "dynamic_shared_memory_bytes")
501}
502
503/// Per-launch execution configuration.
504#[derive(Debug, Clone, Copy)]
505pub enum LaunchAttribute {
506    /// Whether the kernel is launched as a cooperative kernel.
507    Cooperative(bool),
508    /// Dimensions of the cluster in blocks.
509    ClusterDimension(Dim3),
510    /// Cluster scheduling policy preference.
511    ClusterSchedulingPolicy(ClusterSchedulingPolicy),
512    /// Shared memory configuration for the kernel launch.
513    SharedMemoryMode(SharedMemoryMode),
514    /// Priority of the kernel launch.
515    Priority(i32),
516    /// Preferred shared memory carveout percentage.
517    PreferredSharedMemoryCarveout(u32),
518}
519
520impl LaunchAttribute {
521    pub(crate) fn raw(self) -> driver::CUlaunchAttribute {
522        use driver::CUlaunchAttributeID as Id;
523        let mut raw = driver::CUlaunchAttribute::default();
524        match self {
525            Self::Cooperative(value) => {
526                raw.id = Id::CU_LAUNCH_ATTRIBUTE_COOPERATIVE;
527                raw.value.cooperative = i32::from(value);
528            }
529            Self::ClusterDimension(value) => {
530                raw.id = Id::CU_LAUNCH_ATTRIBUTE_CLUSTER_DIMENSION;
531                raw.value.clusterDim = driver::CUlaunchAttributeValue_union__bindgen_ty_1 {
532                    x: value.x,
533                    y: value.y,
534                    z: value.z,
535                };
536            }
537            Self::ClusterSchedulingPolicy(value) => {
538                raw.id = Id::CU_LAUNCH_ATTRIBUTE_CLUSTER_SCHEDULING_POLICY_PREFERENCE;
539                raw.value.clusterSchedulingPolicyPreference = value.into();
540            }
541            Self::SharedMemoryMode(value) => {
542                raw.id = Id::CU_LAUNCH_ATTRIBUTE_SHARED_MEMORY_MODE;
543                raw.value.sharedMemoryMode = value.into();
544            }
545            Self::Priority(value) => {
546                raw.id = Id::CU_LAUNCH_ATTRIBUTE_PRIORITY;
547                raw.value.priority = value;
548            }
549            Self::PreferredSharedMemoryCarveout(value) => {
550                raw.id = Id::CU_LAUNCH_ATTRIBUTE_PREFERRED_SHARED_MEMORY_CARVEOUT;
551                raw.value.sharedMemCarveout = value;
552            }
553        }
554        raw
555    }
556}
557
558impl LaunchConfig {
559    /// Configures attributes for an extended kernel launch.
560    ///
561    /// # Errors
562    ///
563    /// Returns `Error::NotPositive` if a cluster dimension is zero, or `Error::OutOfRange` if the preferred shared-memory carveout exceeds 100 percent.
564    /// Device and kernel compatibility are checked later during preparation or submission.
565    pub fn with_attribute(mut self, attribute: LaunchAttribute) -> Result<Self> {
566        match attribute {
567            LaunchAttribute::ClusterDimension(value) => validate_dim3(value, "cluster_dim")?,
568            LaunchAttribute::PreferredSharedMemoryCarveout(value) if value > 100 => {
569                return Err(Error::out_of_range("preferred shared memory carveout"));
570            }
571            _ => {}
572        }
573
574        let id = attribute.raw().id;
575        self.attributes.retain(|existing| existing.raw().id != id);
576        self.attributes.push(attribute);
577        Ok(self)
578    }
579
580    /// Returns the configured launch attributes.
581    #[must_use]
582    pub fn attributes(&self) -> &[LaunchAttribute] {
583        &self.attributes
584    }
585
586    pub(crate) fn with_raw_config<R>(
587        &self,
588        stream: driver::CUstream,
589        f: impl FnOnce(&driver::CUlaunchConfig) -> Result<R>,
590    ) -> Result<R> {
591        let mut attributes = self.attributes.iter().map(|a| a.raw()).collect::<Vec<_>>();
592        let config = driver::CUlaunchConfig {
593            gridDimX: self.geometry.grid_dim.x,
594            gridDimY: self.geometry.grid_dim.y,
595            gridDimZ: self.geometry.grid_dim.z,
596            blockDimX: self.geometry.block_dim.x,
597            blockDimY: self.geometry.block_dim.y,
598            blockDimZ: self.geometry.block_dim.z,
599            sharedMemBytes: self.shared_memory_bytes_u32(),
600            hStream: stream,
601            attrs: attributes.as_mut_ptr(),
602            numAttrs: to_u32(attributes.len(), "launch attributes")?,
603        };
604        f(&config)
605    }
606
607    pub(crate) unsafe fn launch_raw(
608        &self,
609        function: driver::CUfunction,
610        stream: driver::CUstream,
611        arguments: *mut *mut ffi::c_void,
612    ) -> Result<()> {
613        // SAFETY: `config` and its attribute array live through the closure, and the caller guarantees a live `function` and `stream` in the bound context and `arguments` matching the kernel's parameters.
614        self.with_raw_config(stream, |config| unsafe {
615            try_ffi!(driver::cuLaunchKernelEx(
616                config,
617                function,
618                arguments,
619                ptr::null_mut()
620            ))
621        })
622    }
623}
624
625#[cfg(test)]
626mod tests {
627    use super::*;
628
629    #[test]
630    fn test_launch_config_rejects_zero_grid_dimensions() {
631        let error = LaunchConfig::try_for_1d_grid(0, 128).unwrap_err();
632        assert!(matches!(error, Error::NotPositive { name } if name == "grid_size"));
633
634        let error = LaunchConfig::create(Dim3::new(0, 1, 1), Dim3::new(128, 1, 1), 0).unwrap_err();
635        assert!(matches!(error, Error::NotPositive { name } if name == "grid_dim.x"));
636    }
637
638    #[test]
639    fn test_launch_config_rejects_invalid_shared_memory_size() {
640        let error = LaunchConfig::try_for_1d_grid(1, 128)
641            .unwrap()
642            .with_shared_memory_bytes(u32::MAX as usize + 1)
643            .unwrap_err();
644        assert!(matches!(error, Error::OutOfRange { name } if name == "shared_memory_bytes"));
645    }
646
647    #[test]
648    fn test_launch_config_exposes_checked_shared_memory_u32() {
649        let config = LaunchConfig::try_for_1d_grid(1, 128)
650            .unwrap()
651            .with_shared_memory_bytes(u32::MAX as usize)
652            .unwrap();
653
654        assert_eq!(config.shared_memory_bytes(), u32::MAX as usize);
655        assert_eq!(config.shared_memory_bytes_u32(), u32::MAX);
656    }
657
658    #[test]
659    fn test_occupancy_dynamic_shared_memory_uses_checked_driver_width() {
660        assert_eq!(validate_dynamic_shared_memory_bytes(0).unwrap(), 0);
661        assert_eq!(
662            validate_dynamic_shared_memory_bytes(usize::MAX).unwrap(),
663            usize::MAX as u64
664        );
665    }
666
667    #[test]
668    fn test_launch_config_uses_checked_construction() {
669        let config = LaunchConfig::create(Dim3::new(1, 1, 1), Dim3::new(32, 1, 1), 0).unwrap();
670
671        assert_eq!(config.grid_dim(), Dim3::new(1, 1, 1));
672        assert_eq!(config.block_dim(), Dim3::new(32, 1, 1));
673        assert_eq!(config.shared_memory_bytes(), 0);
674    }
675}