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
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
//! Typed kernel signatures and context-bound launch preparation.

use std::{
    fmt,
    marker::PhantomData,
    mem::{align_of, size_of},
    sync::Arc,
};

use singe_cuda_sys::driver;
use thiserror::Error;

use crate::{
    context::Context,
    device::DeviceAttribute,
    dim::Dim3,
    error::{Error as CudaError, Result, Status},
    graph::{
        ExecutableGraph, Graph, GraphNode,
        owned::{Recordable, Recording},
    },
    green::SmResource,
    module::{
        KernelFunction, KernelParameters, LaunchAttribute, LaunchConfig, LaunchGeometry,
        OccupancyFlags,
    },
    stream::{Stream, StreamCaptureScope},
    submission::{DeviceOperation, Execution, Operation, Resources},
    try_ffi,
    types::{FunctionAttribute, SharedMemoryMode},
    utility::{to_i32, to_u32, to_usize},
    view::NoUninitDeviceRepr,
};

/// Access to the storage addressed by a kernel parameter.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ParameterAccess {
    /// A copied value, with no implied device memory access.
    Value,
    /// Reads initialized elements.
    Read,
    /// Writes elements without reading their previous values.
    Write,
    /// Reads and writes initialized elements.
    ReadWrite,
    /// A pointer whose access contract is supplied by the caller.
    OpaquePointer,
}

/// Host representation of one CUDA parameter, in declaration order.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ParameterLayout {
    size: usize,
    alignment: usize,
    access: ParameterAccess,
}

impl ParameterLayout {
    /// Describes a by-value parameter with initialized representation bytes.
    #[must_use]
    pub const fn value<T: NoUninitDeviceRepr>() -> Self {
        let () = T::LAYOUT;
        Self {
            size: size_of::<T>(),
            alignment: align_of::<T>(),
            access: ParameterAccess::Value,
        }
    }

    /// Describes a CUDA device pointer and its declared memory access.
    #[must_use]
    pub const fn pointer(access: ParameterAccess) -> Self {
        Self {
            size: size_of::<*const ()>(),
            alignment: align_of::<*const ()>(),
            access,
        }
    }

    /// Returns the parameter representation size in bytes.
    #[must_use]
    pub const fn size(self) -> usize {
        self.size
    }

    /// Returns the parameter representation alignment in bytes.
    #[must_use]
    pub const fn alignment(self) -> usize {
        self.alignment
    }

    /// Returns the declared access to storage addressed by this parameter.
    #[must_use]
    pub const fn access(self) -> ParameterAccess {
        self.access
    }
}

/// Number of dimensions used by the kernel's indexing scheme.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum LaunchRank {
    /// Uses only the x axis; grid and block y and z dimensions must all be one.
    One,
    /// Uses the x and y axes; grid and block z dimensions must be one.
    Two,
    /// Permits all three grid and block axes.
    #[default]
    Three,
}

/// Integer representation used for thread coordinates.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CoordinateWidth {
    /// Nonnegative coordinates representable by a unsigned 32-bit integer.
    U32,
    /// Nonnegative coordinates representable by a signed 32-bit integer.
    I32,
    /// Nonnegative coordinates representable by a unsigned 64-bit integer.
    U64,
    /// Nonnegative coordinates representable by a signed 64-bit integer.
    I64,
}

impl CoordinateWidth {
    const fn max(self) -> u128 {
        match self {
            Self::U32 => u32::MAX as u128,
            Self::I32 => i32::MAX as u128,
            Self::U64 => u64::MAX as u128,
            Self::I64 => i64::MAX as u128,
        }
    }
}

/// Block dimensions accepted by the kernel.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum BlockRequirement {
    /// Adds no block-shape restriction beyond CUDA function and device limits.
    #[default]
    Any,
    /// Requires these exact thread dimensions for each block.
    Exact(Dim3),
    /// The total number of threads must be a nonzero multiple of this value.
    MultipleOf(u32),
    /// Maximum total number of threads in a block.
    MaxThreads(u32),
}

/// Dynamic shared memory required by each block.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SharedMemoryRequirement {
    /// Adds no dynamic shared-memory requirement beyond CUDA function and device limits.
    #[default]
    Any,
    /// Requires exactly this many dynamic shared-memory bytes per block.
    Exact(usize),
    /// Requires at least this many dynamic shared-memory bytes per block.
    AtLeast(usize),
    /// Inclusive kernel-specific bounds on dynamic shared memory.
    Range {
        /// Minimum permitted dynamic shared-memory bytes per block, inclusive.
        min: usize,
        /// Maximum permitted dynamic shared-memory bytes per block, inclusive.
        max: usize,
    },
}

/// Kernel requirements checked against a configuration and its actual context.
///
/// Coordinate requirements check the launched extent, including padded threads.
/// Leave them unspecified only when the kernel has no corresponding restriction.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct LaunchRequirements {
    /// Axes used by the kernel's indexing scheme.
    /// Unused grid and block axes must equal one.
    pub rank: LaunchRank,
    /// Optional integer width bounding the largest launched coordinate on every axis, including padded threads.
    pub axis_coordinates: Option<CoordinateWidth>,
    /// Optional integer width bounding the largest flattened coordinate across the complete launched grid, including padded threads.
    pub linear_coordinates: Option<CoordinateWidth>,
    /// Kernel-specific constraints on the block shape or thread count.
    pub block: BlockRequirement,
    /// Kernel-specific dynamic shared-memory byte requirements per block.
    pub shared_memory: SharedMemoryRequirement,
    /// Minimum device compute capability as `(major, minor)`, or `None` for no additional minimum.
    pub min_compute_capability: Option<(u32, u32)>,
    /// Required cluster dimensions in blocks, or `None` for no signature-specific cluster shape.
    /// Native kernel requirements still apply.
    pub cluster: Option<Dim3>,
    /// Whether the launch must explicitly enable cooperative execution.
    /// A false value also permits cooperative launches when the device supports them.
    pub cooperative: bool,
}

impl Default for LaunchRequirements {
    fn default() -> Self {
        Self::DEFAULT
    }
}

impl LaunchRequirements {
    /// No restrictions beyond the CUDA function and device limits.
    pub const DEFAULT: Self = Self {
        rank: LaunchRank::Three,
        axis_coordinates: None,
        linear_coordinates: None,
        block: BlockRequirement::Any,
        shared_memory: SharedMemoryRequirement::Any,
        min_compute_capability: None,
        cluster: None,
        cooperative: false,
    };
}

/// A kernel ABI and its launch requirements.
///
/// # Safety
///
/// `encode` must encode exactly `PARAMETERS`, in order, using the declared CUDA representation and access modes.
/// `raw_arguments` must preserve that order and check every typed view's actual context.
/// By-value representations must contain no uninitialized bytes.
/// The requirements must describe the kernel being bound.
/// This contract does not certify argument-dependent memory bounds or output coverage.
pub unsafe trait KernelSignature: 'static {
    /// Typed values and borrowed device views in declaration order.
    type Arguments<'a>;

    /// CUDA parameter values, including raw device addresses, in declaration order.
    type RawArguments: Copy + 'static;

    /// Host ABI layouts of the CUDA parameters, in declaration order.
    const PARAMETERS: &'static [ParameterLayout];

    /// Indexing and execution requirements checked when binding a launch configuration.
    const REQUIREMENTS: LaunchRequirements;

    /// Checks device-view contexts and converts typed arguments into CUDA parameter values.
    ///
    /// # Errors
    ///
    /// Returns an error if a typed device view belongs to another context or the implementation cannot convert the supplied values to its raw argument representation.
    /// Implementations may impose additional argument-specific checks.
    fn raw_arguments(
        arguments: Self::Arguments<'_>,
        context: &Arc<Context>,
    ) -> Result<Self::RawArguments>;

    /// Copies raw argument values into storage valid for the duration of `f`.
    fn encode<R>(arguments: Self::RawArguments, f: impl FnOnce(KernelParameters<'_>) -> R) -> R;
}

/// Failure to match a kernel's ABI, indexing or execution requirements.
#[derive(Debug, Clone, PartialEq, Eq, Error)]
#[non_exhaustive]
pub enum LaunchContractError {
    /// The native function parameter count differs from the signature.
    #[error("kernel parameter count mismatch (expected {expected}, got {actual})")]
    ParameterCount {
        /// Number of parameters declared by the signature.
        expected: usize,
        /// Number of parameters reported by CUDA.
        actual: usize,
    },
    /// A native parameter offset or size differs from the signature's host ABI layout.
    #[error(
        "kernel parameter {index} layout mismatch (expected offset {expected_offset}, size {expected_size}; got offset {actual_offset}, size {actual_size})"
    )]
    ParameterLayout {
        /// Zero-based parameter index.
        index: usize,
        /// Byte offset computed from the signature's preceding parameter sizes and alignments.
        expected_offset: usize,
        /// Parameter size in bytes declared by the signature.
        expected_size: usize,
        /// Parameter byte offset reported by CUDA.
        actual_offset: usize,
        /// Parameter size in bytes reported by CUDA.
        actual_size: usize,
    },
    /// Nonunit dimensions occur on axes outside the kernel's indexing rank.
    #[error("launch dimensions exceed the kernel's {rank:?} dimensional indexing")]
    Rank {
        /// Indexing rank required by the kernel.
        rank: LaunchRank,
    },
    /// The configured block violates a kernel-specific block requirement.
    #[error("block dimensions {actual:?} do not satisfy {required:?}")]
    Block {
        /// Kernel-specific block requirement.
        required: BlockRequirement,
        /// Configured block dimensions in threads.
        actual: Dim3,
    },
    /// A requested launch quantity exceeds its device, function, or coordinate limit.
    #[error("`{name}` exceeds its limit (requested {requested}, limit {limit})")]
    Limit {
        /// Name of the checked launch quantity.
        name: &'static str,
        /// Requested quantity in the units identified by `name`.
        requested: u128,
        /// Maximum permitted quantity in the same units as `requested`.
        limit: u128,
    },
    /// Dynamic shared memory violates the kernel's byte requirement.
    #[error("dynamic shared memory {actual} does not satisfy {required:?}")]
    SharedMemory {
        /// Kernel-specific dynamic shared-memory requirement.
        required: SharedMemoryRequirement,
        /// Configured dynamic shared-memory bytes per block.
        actual: usize,
    },
    /// The device's compute capability is below the kernel's required minimum.
    #[error("compute capability {actual:?} is below {required:?}")]
    Architecture {
        /// Minimum compute capability as `(major, minor)`.
        required: (u32, u32),
        /// Device compute capability as `(major, minor)`.
        actual: (u32, u32),
    },
    /// Configured cluster dimensions disagree with the signature or native kernel requirement.
    #[error("cluster dimensions {actual:?} do not satisfy {required:?}")]
    Cluster {
        /// Required cluster dimensions in blocks, when present.
        required: Option<Dim3>,
        /// Effective launch cluster dimensions in blocks, when present.
        actual: Option<Dim3>,
    },
    /// The native function requires an explicit cluster size, but none is available.
    #[error("kernel requires explicit cluster dimensions")]
    ClusterRequired,
    /// A cluster launch was requested on a device without cluster-launch support.
    #[error("device does not support cluster launches")]
    ClusterUnsupported,
    /// The cluster dimensions are zero or do not divide the grid dimensions.
    #[error("grid dimensions {grid:?} are incompatible with cluster dimensions {cluster:?}")]
    ClusterGrid {
        /// Configured grid dimensions in blocks.
        grid: Dim3,
        /// Effective cluster dimensions in blocks.
        cluster: Dim3,
    },
    /// A required cooperative attribute is absent, or the device does not support the requested cooperative launch.
    #[error("cooperative launch is required or unsupported on this device")]
    Cooperative,
    /// An explicit shared-memory mode was requested on a driver that cannot query or support shared-memory modes.
    #[error("shared-memory mode {mode:?} is unsupported by the current driver")]
    SharedMemoryModeUnsupported {
        /// Requested per-launch shared-memory mode.
        mode: SharedMemoryMode,
    },
    /// The product of grid and block volumes cannot be represented in 128 bits.
    #[error("linear launch coordinates exceed 128 bits")]
    CoordinateOverflow,
    /// Computing a parameter offset or end overflows the host address space.
    #[error("kernel parameter layout overflows the host address space")]
    ParameterLayoutOverflow,
}

/// A typed kernel and checked configuration retaining the native code owner.
///
/// Preparation checks the signature and launch requirements.
/// It does not launch work, initialize output storage, or prove argument-dependent accesses valid.
/// Immediate submissions, capture and graph-node creation share this configuration.
/// Executable-node updates reuse its geometry and preserve the executable's existing attributes.
pub struct PreparedLaunch<K: KernelSignature> {
    function: KernelFunction,
    config: LaunchConfig,
    _signature: PhantomData<fn() -> K>,
}

impl<K: KernelSignature> fmt::Debug for PreparedLaunch<K> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("PreparedLaunch")
            .field("function", &self.function)
            .field("config", &self.config)
            .finish()
    }
}

impl<K: KernelSignature> Clone for PreparedLaunch<K> {
    fn clone(&self) -> Self {
        Self {
            function: self.function.clone(),
            config: self.config.clone(),
            _signature: PhantomData,
        }
    }
}

impl<K: KernelSignature> PreparedLaunch<K> {
    /// Binds this signature to a kernel and checks its ABI and launch requirements.
    ///
    /// # Safety
    ///
    /// `K`'s access modes and launch requirements must describe this function.
    /// Parameter count and representation mismatches are rejected.
    /// CUDA metadata does not verify struct field layouts or semantic identity.
    /// Explicit struct mappings must match the device field layout.
    ///
    /// # Errors
    ///
    /// Returns a [`LaunchContractError`] for parameter count or layout mismatches, layout overflow, incompatible launch requirements, or exceeded function or device limits.
    /// Also propagates context binding, native parameter or attribute query, occupancy, resource query, and integer conversion errors.
    /// No work is launched on success.
    pub unsafe fn create(function: &KernelFunction, config: LaunchConfig) -> Result<Self> {
        validate_parameters::<K>(function)?;
        validate_requirements(function, &config, K::REQUIREMENTS)?;
        Ok(Self {
            function: function.clone(),
            config,
            _signature: PhantomData,
        })
    }

    /// Returns the retained context-specific kernel function.
    #[must_use]
    pub fn function(&self) -> &KernelFunction {
        &self.function
    }

    /// Returns the checked launch configuration.
    #[must_use]
    pub fn config(&self) -> &LaunchConfig {
        &self.config
    }

    /// Returns the context in which the function's module was loaded.
    #[must_use]
    pub fn context(&self) -> &Arc<Context> {
        self.function.module().context()
    }

    /// Checks that `stream` belongs to the prepared kernel's context.
    ///
    /// # Errors
    ///
    /// Returns `CudaError::StreamContextMismatch` if `stream` belongs to a different context.
    pub fn validate_stream(&self, stream: &Stream) -> Result<()> {
        if stream.context() != self.context() {
            return Err(CudaError::StreamContextMismatch);
        }
        Ok(())
    }

    /// Submits a launch on an explicit stream in this kernel's context.
    ///
    /// # Safety
    ///
    /// Values and views must satisfy the kernel's bounds, initialization and semantic requirements.
    /// Preserve storage lifetimes and exclusive writable access until execution completes, including every graph replay when `stream` is capturing.
    /// Keep this prepared launch or another owner of its kernel code alive through completion.
    ///
    /// # Errors
    ///
    /// Propagates typed argument conversion and view-context errors from [`KernelSignature::raw_arguments`].
    /// Returns `CudaError::StreamContextMismatch` if `stream` belongs to another context, and propagates context binding and native launch errors from [`KernelFunction::launch_async`].
    pub unsafe fn launch_async(&self, arguments: K::Arguments<'_>, stream: &Stream) -> Result<()> {
        let arguments = K::raw_arguments(arguments, self.context())?;
        // SAFETY: `raw_arguments` checked the views' context, and the caller's guarantees on values, storage lifetimes, and code ownership are those `launch_encoded` requires.
        unsafe { self.launch_encoded(arguments, stream) }
    }

    /// Records a launch in the active capture and retains the kernel's code for replay.
    ///
    /// # Safety
    ///
    /// Values and views must satisfy the kernel's bounds, initialization and semantic requirements for every replay.
    /// Preserve storage lifetimes and exclusive writable access until all graph executions complete.
    /// Keep a graph, executable or another code owner alive until queued executions complete.
    ///
    /// # Errors
    ///
    /// Propagates typed argument conversion and view-context errors from [`KernelSignature::raw_arguments`].
    /// Returns `CudaError::StreamContextMismatch` if the capture stream belongs to another context, and propagates context binding and native launch errors.
    pub unsafe fn record(
        &self,
        arguments: K::Arguments<'_>,
        scope: &StreamCaptureScope<'_>,
    ) -> Result<()> {
        let arguments = K::raw_arguments(arguments, self.context())?;
        self.validate_stream(scope.stream())?;
        scope.retain_module(self.function.module());
        // SAFETY: `raw_arguments` checked the views' context, the capture retains the module above, and the caller's guarantees for every replay cover what `launch_encoded` requires.
        unsafe { self.launch_encoded(arguments, scope.stream()) }
    }

    /// Adds a graph node with this launch's configuration and retains the kernel's code.
    ///
    /// # Safety
    ///
    /// Values and views must satisfy the kernel's bounds, initialization and semantic requirements for every replay.
    /// Preserve storage lifetimes and exclusive writable access until all graph executions complete.
    /// Keep a graph, executable or another code owner alive until queued executions complete.
    ///
    /// # Errors
    ///
    /// Propagates typed argument conversion and view-context errors from [`KernelSignature::raw_arguments`].
    /// Also propagates graph-context, dependency ownership, context binding, and native node creation or launch-attribute errors from [`KernelFunction::add_to_graph`].
    pub unsafe fn add_to_graph(
        &self,
        arguments: K::Arguments<'_>,
        graph: &mut Graph,
        dependencies: &[GraphNode],
    ) -> Result<GraphNode> {
        let arguments = K::raw_arguments(arguments, self.context())?;
        // SAFETY: `self.function` and `self.config` were checked against `K` when this launch was prepared, `raw_arguments` checked the views' context, and the caller's guarantees are those `KernelFunction::add_to_graph` requires.
        K::encode(arguments, |params| unsafe {
            self.function
                .add_to_graph(graph, dependencies, &self.config, params)
        })
    }

    /// Updates an executable node with this launch's geometry and arguments, retaining the kernel's code.
    ///
    /// # Safety
    ///
    /// Values and views must satisfy the kernel's bounds, initialization and semantic requirements for all future executions.
    /// Preserve storage lifetimes and exclusive writable access until all executions using them complete.
    /// Keep the executable or another code owner alive until queued executions complete.
    /// Only this launch's geometry is applied; executable attributes remain unchanged and must satisfy `K`.
    ///
    /// # Errors
    ///
    /// Propagates typed argument conversion and view-context errors from [`KernelSignature::raw_arguments`].
    /// Also propagates executable-context, node ownership, context binding, and native update errors from [`KernelFunction::set_graph_node_params`].
    pub unsafe fn set_graph_node_params(
        &self,
        arguments: K::Arguments<'_>,
        executable: &mut ExecutableGraph,
        node: &GraphNode,
    ) -> Result<()> {
        let arguments = K::raw_arguments(arguments, self.context())?;
        // SAFETY: `self.function` and `self.config` were checked against `K` when this launch was prepared, `raw_arguments` checked the views' context, and the caller's guarantees are those `KernelFunction::set_graph_node_params` requires.
        K::encode(arguments, |params| unsafe {
            self.function
                .set_graph_node_params(executable, node, self.config.geometry(), params)
        })
    }

    // Launches converted arguments on `stream`.
    // The caller guarantees the arguments satisfy the kernel's requirements and keeps their storage and the kernel's code alive until completion.
    unsafe fn launch_encoded(&self, arguments: K::RawArguments, stream: &Stream) -> Result<()> {
        self.validate_stream(stream)?;
        // SAFETY: `self.function` and `self.config` were checked against `K` when this launch was prepared, the stream's context is checked above, and the caller's argument guarantees are those `KernelFunction::launch_async` requires.
        K::encode(arguments, |params| unsafe {
            self.function.launch_async(&self.config, params, stream)
        })
    }
}

impl KernelFunction {
    /// Updates an executable node's geometry and arguments, retaining this kernel's code.
    ///
    /// Launch attributes remain unchanged.
    ///
    /// # Safety
    ///
    /// `K` must describe this function and the executable's existing attributes must satisfy it.
    /// Arguments must satisfy the kernel's bounds, initialization and aliasing requirements for every execution.
    /// Keep storage and the executable or another code owner alive until queued executions complete.
    ///
    /// # Errors
    ///
    /// Returns an error for ABI, view-context or geometry mismatches, or if CUDA rejects the update.
    pub unsafe fn set_typed_graph_node_params<K: KernelSignature>(
        &self,
        executable: &mut ExecutableGraph,
        node: &GraphNode,
        geometry: &LaunchGeometry,
        arguments: K::Arguments<'_>,
    ) -> Result<()> {
        let arguments = K::raw_arguments(arguments, self.module().context())?;
        validate_parameters::<K>(self)?;
        validate_kernel_geometry(self, geometry, K::REQUIREMENTS)?;
        // SAFETY: `raw_arguments` checked the views' context, the parameter layout and geometry are checked against `K` above, and the caller's guarantees are those `set_graph_node_params` requires.
        K::encode(arguments, |params| unsafe {
            self.set_graph_node_params(executable, node, geometry, params)
        })
    }
}

fn validate_parameters<K: KernelSignature>(function: &KernelFunction) -> Result<()> {
    function.module().context().bind()?;
    let mut count = 0;
    // SAFETY: `count` is a writable local, and `function` retains its module, whose context is bound above.
    unsafe {
        try_ffi!(driver::cuFuncGetParamCount(
            function.as_raw().as_raw(),
            &raw mut count
        ))?;
    }

    if to_usize(count, "kernel parameter count")? != K::PARAMETERS.len() {
        return Err(LaunchContractError::ParameterCount {
            expected: K::PARAMETERS.len(),
            actual: to_usize(count, "kernel parameter count")?,
        }
        .into());
    }

    let mut expected_offset = 0_usize;
    for (index, parameter) in K::PARAMETERS.iter().enumerate() {
        let padding = expected_offset.wrapping_neg() & (parameter.alignment - 1);
        expected_offset = expected_offset
            .checked_add(padding)
            .ok_or(LaunchContractError::ParameterLayoutOverflow)?;
        let mut offset = 0;
        let mut size = 0;
        let native_index = index
            .try_into()
            .map_err(|_| CudaError::out_of_range("kernel parameter index"))?;
        // SAFETY: `offset` and `size` are writable locals, and `function` retains its module, whose context is bound above.
        unsafe {
            try_ffi!(driver::cuFuncGetParamInfo(
                function.as_raw().as_raw(),
                native_index,
                &raw mut offset,
                &raw mut size
            ))?;
        }

        if to_usize(offset, "kernel parameter offset")? != expected_offset
            || to_usize(size, "kernel parameter size")? != parameter.size
        {
            return Err(LaunchContractError::ParameterLayout {
                index,
                expected_offset,
                expected_size: parameter.size,
                actual_offset: to_usize(offset, "kernel parameter offset")?,
                actual_size: to_usize(size, "kernel parameter size")?,
            }
            .into());
        }

        expected_offset = expected_offset
            .checked_add(parameter.size)
            .ok_or(LaunchContractError::ParameterLayoutOverflow)?;
    }
    Ok(())
}

// Widens a native attribute or occupancy count, which CUDA reports as a non-negative `i32`, for the limit checks.
fn native_limit(value: i32) -> Result<u128> {
    u128::try_from(value).map_err(|_| CudaError::out_of_range("native launch limit"))
}

fn check_limit(name: &'static str, requested: u128, limit: u128) -> Result<()> {
    if requested > limit {
        return Err(LaunchContractError::Limit {
            name,
            requested,
            limit,
        }
        .into());
    }
    Ok(())
}

fn volume(dim: Dim3) -> u128 {
    u128::from(dim.x) * u128::from(dim.y) * u128::from(dim.z)
}

fn validate_geometry(
    function: &KernelFunction,
    geometry: &LaunchGeometry,
    required: LaunchRequirements,
) -> Result<()> {
    let grid = geometry.grid_dim();
    let block = geometry.block_dim();
    match required.rank {
        LaunchRank::One if grid.y != 1 || grid.z != 1 || block.y != 1 || block.z != 1 => {
            return Err(LaunchContractError::Rank {
                rank: required.rank,
            }
            .into());
        }
        LaunchRank::Two if grid.z != 1 || block.z != 1 => {
            return Err(LaunchContractError::Rank {
                rank: required.rank,
            }
            .into());
        }
        _ => {}
    }

    match required.block {
        BlockRequirement::MaxThreads(n) if volume(block) > u128::from(n) => {
            return Err(LaunchContractError::Block {
                required: required.block,
                actual: block,
            }
            .into());
        }
        BlockRequirement::Exact(dim) if dim != block => {
            return Err(LaunchContractError::Block {
                required: required.block,
                actual: block,
            }
            .into());
        }
        BlockRequirement::MultipleOf(n)
            if n == 0 || !volume(block).is_multiple_of(u128::from(n)) =>
        {
            return Err(LaunchContractError::Block {
                required: required.block,
                actual: block,
            }
            .into());
        }
        _ => {}
    }

    let context = function.module().context();
    let device = context.device();
    for (g, b, grid_attr, block_attr) in [
        (
            grid.x,
            block.x,
            DeviceAttribute::MaxGridDimX,
            DeviceAttribute::MaxBlockDimX,
        ),
        (
            grid.y,
            block.y,
            DeviceAttribute::MaxGridDimY,
            DeviceAttribute::MaxBlockDimY,
        ),
        (
            grid.z,
            block.z,
            DeviceAttribute::MaxGridDimZ,
            DeviceAttribute::MaxBlockDimZ,
        ),
    ] {
        check_limit(
            "grid dimension",
            u128::from(g),
            native_limit(device.attribute(grid_attr)?)?,
        )?;
        check_limit(
            "block dimension",
            u128::from(b),
            native_limit(device.attribute(block_attr)?)?,
        )?;
        if let Some(width) = required.axis_coordinates {
            check_limit(
                "axis coordinate",
                u128::from(g) * u128::from(b) - 1,
                width.max(),
            )?;
        }
    }

    if let Some(width) = required.linear_coordinates {
        check_limit(
            "linear coordinate",
            volume(grid)
                .checked_mul(volume(block))
                .ok_or(LaunchContractError::CoordinateOverflow)?
                - 1,
            width.max(),
        )?;
    }

    let threads = volume(block);
    check_limit(
        "threads per block",
        threads,
        native_limit(device.attribute(DeviceAttribute::MaxThreadsPerBlock)?)?,
    )?;
    check_limit(
        "kernel threads per block",
        threads,
        native_limit(function.attribute(FunctionAttribute::MaxThreadsPerBlock)?)?,
    )?;
    Ok(())
}

fn validate_kernel_geometry(
    function: &KernelFunction,
    geometry: &LaunchGeometry,
    required: LaunchRequirements,
) -> Result<()> {
    validate_geometry(function, geometry, required)?;
    let device = function.module().context().device();
    let shared = geometry.shared_memory_bytes();
    match required.shared_memory {
        SharedMemoryRequirement::Range { min, max } if shared < min || shared > max => {
            return Err(LaunchContractError::SharedMemory {
                required: required.shared_memory,
                actual: shared,
            }
            .into());
        }
        SharedMemoryRequirement::Exact(n) if shared != n => {
            return Err(LaunchContractError::SharedMemory {
                required: required.shared_memory,
                actual: shared,
            }
            .into());
        }
        SharedMemoryRequirement::AtLeast(n) if shared < n => {
            return Err(LaunchContractError::SharedMemory {
                required: required.shared_memory,
                actual: shared,
            }
            .into());
        }
        _ => {}
    }

    if let Some(minimum) = required.min_compute_capability {
        let actual = (
            to_u32(
                device.attribute(DeviceAttribute::ComputeCapabilityMajor)?,
                "native attribute",
            )?,
            to_u32(
                device.attribute(DeviceAttribute::ComputeCapabilityMinor)?,
                "native attribute",
            )?,
        );
        if actual < minimum {
            return Err(LaunchContractError::Architecture {
                required: minimum,
                actual,
            }
            .into());
        }
    }
    Ok(())
}

fn validate_requirements(
    function: &KernelFunction,
    config: &LaunchConfig,
    required: LaunchRequirements,
) -> Result<()> {
    validate_kernel_geometry(function, config.geometry(), required)?;
    let context = function.module().context();
    let device = context.device();
    let grid = config.grid_dim();
    let threads = volume(config.block_dim());
    let shared = config.shared_memory_bytes();
    check_limit(
        "dynamic shared memory",
        shared as u128,
        dynamic_shared_memory_limit(function, config)?,
    )?;
    let mut cluster = None;
    let mut cooperative = false;
    for attribute in config.attributes() {
        match attribute {
            LaunchAttribute::ClusterDimension(dim) => cluster = Some(*dim),
            LaunchAttribute::Cooperative(value) => cooperative = *value,
            _ => {}
        }
    }

    let native_cluster = Dim3::new(
        to_u32(
            function.attribute(FunctionAttribute::RequiredClusterWidth)?,
            "native attribute",
        )?,
        to_u32(
            function.attribute(FunctionAttribute::RequiredClusterHeight)?,
            "native attribute",
        )?,
        to_u32(
            function.attribute(FunctionAttribute::RequiredClusterDepth)?,
            "native attribute",
        )?,
    );
    let native_cluster = (native_cluster.x != 0 || native_cluster.y != 0 || native_cluster.z != 0)
        .then_some(native_cluster);
    if let (Some(actual), Some(native)) = (cluster, native_cluster)
        && actual != native
    {
        return Err(LaunchContractError::Cluster {
            required: Some(native),
            actual: Some(actual),
        }
        .into());
    }

    let cluster = cluster.or(native_cluster);
    if required.cluster.is_some() && cluster != required.cluster {
        return Err(LaunchContractError::Cluster {
            required: required.cluster,
            actual: cluster,
        }
        .into());
    }

    if function.attribute(FunctionAttribute::ClusterSizeMustBeSet)? != 0 && cluster.is_none() {
        return Err(LaunchContractError::ClusterRequired.into());
    }

    if let Some(dim) = cluster {
        if device.attribute(DeviceAttribute::ClusterLaunch)? == 0 {
            return Err(LaunchContractError::ClusterUnsupported.into());
        }

        if dim.x == 0
            || dim.y == 0
            || dim.z == 0
            || !grid.x.is_multiple_of(dim.x)
            || !grid.y.is_multiple_of(dim.y)
            || !grid.z.is_multiple_of(dim.z)
        {
            return Err(LaunchContractError::ClusterGrid { grid, cluster: dim }.into());
        }

        let limit = function.occupancy_max_potential_cluster_size(config)?;
        check_limit("cluster blocks", volume(dim), native_limit(limit)?)?;
    }

    if required.cooperative && !cooperative
        || cooperative && device.attribute(DeviceAttribute::CooperativeLaunch)? == 0
    {
        return Err(LaunchContractError::Cooperative.into());
    }

    if let (true, Some(cluster)) = (cooperative, cluster) {
        let active = function.occupancy_max_active_clusters(config)?;
        check_limit(
            "cooperative grid clusters",
            volume(grid) / volume(cluster),
            native_limit(active)?,
        )?;
    } else if cooperative {
        let active = function.occupancy_max_active_blocks_per_multiprocessor(
            to_i32(threads, "block thread count")?,
            shared,
            OccupancyFlags::DEFAULT,
        )?;
        let sms = SmResource::for_context(context)?.sm_count();
        check_limit(
            "cooperative grid blocks",
            volume(grid),
            native_limit(active)? * u128::from(sms),
        )?;
    }
    Ok(())
}

fn dynamic_shared_memory_limit(function: &KernelFunction, config: &LaunchConfig) -> Result<u128> {
    let requested = config.attributes().iter().find_map(|attribute| {
        if let LaunchAttribute::SharedMemoryMode(mode) = attribute {
            Some(*mode)
        } else {
            None
        }
    });
    let function_mode = match function.shared_memory_mode() {
        Ok(mode) => mode,
        // A live function on a driver without shared-memory modes rejects this attribute.
        // Ordinary launches still use the function's dynamic-memory limit.
        Err(CudaError::Cuda {
            code: Status::InvalidValue | Status::NotSupported,
            ..
        }) => match requested {
            None => SharedMemoryMode::Default,
            Some(mode) => {
                return Err(LaunchContractError::SharedMemoryModeUnsupported { mode }.into());
            }
        },
        Err(error) => return Err(error),
    };
    let mode = requested.unwrap_or(function_mode);
    let device = function.module().context().device();
    let capacity = match mode {
        SharedMemoryMode::Default => {
            return native_limit(function.attribute(FunctionAttribute::MaxDynamicSharedSizeBytes)?);
        }
        SharedMemoryMode::RequirePortable => {
            native_limit(device.attribute(DeviceAttribute::MaxSharedMemoryPerBlock)?)?
        }
        SharedMemoryMode::AllowNonPortable => {
            native_limit(device.attribute(DeviceAttribute::MaxSharedMemoryPerBlockOptin)?)?
        }
        SharedMemoryMode::AllowOversizedSharedMemory
        | SharedMemoryMode::PreferOversizedSharedMemory => {
            let optin = device.attribute(DeviceAttribute::MaxSharedMemoryPerBlockOptin)?;
            let oversized = device.attribute(DeviceAttribute::MaxOversizedSharedMemoryPerBlock)?;
            native_limit(optin.max(oversized))?
        }
    };
    let static_bytes = native_limit(function.attribute(FunctionAttribute::SharedSizeBytes)?)?;
    check_limit("static shared memory", static_bytes, capacity)?;
    Ok(capacity - static_bytes)
}

/// Prepared owned kernel work with an explicit resource and access contract.
#[derive(Debug)]
pub struct KernelOperation<K: KernelSignature, T> {
    launch: PreparedLaunch<K>,
    arguments: K::RawArguments,
    resources: Resources,
    output: T,
}

impl<K: KernelSignature> PreparedLaunch<K> {
    /// Binds owned resources to this prepared launch without enqueueing work.
    ///
    /// # Safety
    ///
    /// Arguments must satisfy the kernel's bounds, value, aliasing and output coverage contracts.
    /// Retain every pointed-to allocation and declare all accesses in `resources`.
    /// `output` must preserve pending initialization until successful completion, including capture.
    ///
    /// # Errors
    ///
    /// Propagates typed argument conversion and view-context errors from [`KernelSignature::raw_arguments`].
    pub unsafe fn into_operation<T: 'static>(
        self,
        arguments: K::Arguments<'_>,
        mut resources: Resources,
        output: T,
    ) -> Result<KernelOperation<K, T>> {
        let arguments = K::raw_arguments(arguments, self.context())?;
        resources.retain(Arc::new(self.function.module().clone()));
        Ok(KernelOperation {
            launch: self,
            arguments,
            resources,
            output,
        })
    }
}

// SAFETY: `into_operation`'s caller declared every owner and access in `resources` and supplied a pending `output`, and `enqueue` registers them through `Execution::enqueue` before launching.
unsafe impl<K: KernelSignature, T: 'static> Operation for KernelOperation<K, T> {
    type Pending = Self::Output;

    type Output = T;

    fn enqueue(self, execution: &mut Execution) -> Result<T> {
        // SAFETY: `resources` retain every buffer the arguments address, as `into_operation` requires, and `launch_encoded` runs on the stream that orders those accesses.
        unsafe {
            execution.enqueue(self.resources, |stream| {
                self.launch.launch_encoded(self.arguments, stream)
            })?;
        }
        Ok(self.output)
    }

    unsafe fn resolve(pending: Self::Pending) -> Result<Self::Output> {
        Ok(pending)
    }
}

// SAFETY: `resolve` returns its input unchanged, and `enqueue` schedules the launch without host resolution.
unsafe impl<K: KernelSignature, T: 'static> DeviceOperation for KernelOperation<K, T> {}

// SAFETY: `record` registers the declared owners and accesses with `Recording` before the launch, the module is among the retained resources, and `output` stays pending as `into_operation` requires.
unsafe impl<K: KernelSignature, T: 'static> Recordable for KernelOperation<K, T> {
    type Output = T;

    fn record(self, recording: &mut Recording) -> Result<T> {
        // SAFETY: `resources` retain every buffer the arguments address for every replay, as `into_operation` requires, and the launch records on the capturing stream.
        unsafe {
            recording.enqueue(self.resources, |stream| {
                self.launch.launch_encoded(self.arguments, stream)
            })?;
        }
        Ok(self.output)
    }
}