1use std::{
4 fmt,
5 marker::PhantomData,
6 mem::{align_of, size_of},
7 sync::Arc,
8};
9
10use singe_cuda_sys::driver;
11use thiserror::Error;
12
13use crate::{
14 context::Context,
15 device::DeviceAttribute,
16 dim::Dim3,
17 error::{Error as CudaError, Result, Status},
18 graph::{
19 ExecutableGraph, Graph, GraphNode,
20 owned::{Recordable, Recording},
21 },
22 green::SmResource,
23 module::{
24 KernelFunction, KernelParameters, LaunchAttribute, LaunchConfig, LaunchGeometry,
25 OccupancyFlags,
26 },
27 stream::{Stream, StreamCaptureScope},
28 submission::{DeviceOperation, Execution, Operation, Resources},
29 try_ffi,
30 types::{FunctionAttribute, SharedMemoryMode},
31 utility::{to_i32, to_u32, to_usize},
32 view::NoUninitDeviceRepr,
33};
34
35#[derive(Debug, Clone, Copy, PartialEq, Eq)]
37pub enum ParameterAccess {
38 Value,
40 Read,
42 Write,
44 ReadWrite,
46 OpaquePointer,
48}
49
50#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52pub struct ParameterLayout {
53 size: usize,
54 alignment: usize,
55 access: ParameterAccess,
56}
57
58impl ParameterLayout {
59 #[must_use]
61 pub const fn value<T: NoUninitDeviceRepr>() -> Self {
62 let () = T::LAYOUT;
63 Self {
64 size: size_of::<T>(),
65 alignment: align_of::<T>(),
66 access: ParameterAccess::Value,
67 }
68 }
69
70 #[must_use]
72 pub const fn pointer(access: ParameterAccess) -> Self {
73 Self {
74 size: size_of::<*const ()>(),
75 alignment: align_of::<*const ()>(),
76 access,
77 }
78 }
79
80 #[must_use]
82 pub const fn size(self) -> usize {
83 self.size
84 }
85
86 #[must_use]
88 pub const fn alignment(self) -> usize {
89 self.alignment
90 }
91
92 #[must_use]
94 pub const fn access(self) -> ParameterAccess {
95 self.access
96 }
97}
98
99#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
101pub enum LaunchRank {
102 One,
104 Two,
106 #[default]
108 Three,
109}
110
111#[derive(Debug, Clone, Copy, PartialEq, Eq)]
113pub enum CoordinateWidth {
114 U32,
116 I32,
118 U64,
120 I64,
122}
123
124impl CoordinateWidth {
125 const fn max(self) -> u128 {
126 match self {
127 Self::U32 => u32::MAX as u128,
128 Self::I32 => i32::MAX as u128,
129 Self::U64 => u64::MAX as u128,
130 Self::I64 => i64::MAX as u128,
131 }
132 }
133}
134
135#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
137pub enum BlockRequirement {
138 #[default]
140 Any,
141 Exact(Dim3),
143 MultipleOf(u32),
145 MaxThreads(u32),
147}
148
149#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
151pub enum SharedMemoryRequirement {
152 #[default]
154 Any,
155 Exact(usize),
157 AtLeast(usize),
159 Range {
161 min: usize,
163 max: usize,
165 },
166}
167
168#[derive(Debug, Clone, Copy, PartialEq, Eq)]
173pub struct LaunchRequirements {
174 pub rank: LaunchRank,
177 pub axis_coordinates: Option<CoordinateWidth>,
179 pub linear_coordinates: Option<CoordinateWidth>,
181 pub block: BlockRequirement,
183 pub shared_memory: SharedMemoryRequirement,
185 pub min_compute_capability: Option<(u32, u32)>,
187 pub cluster: Option<Dim3>,
190 pub cooperative: bool,
193}
194
195impl Default for LaunchRequirements {
196 fn default() -> Self {
197 Self::DEFAULT
198 }
199}
200
201impl LaunchRequirements {
202 pub const DEFAULT: Self = Self {
204 rank: LaunchRank::Three,
205 axis_coordinates: None,
206 linear_coordinates: None,
207 block: BlockRequirement::Any,
208 shared_memory: SharedMemoryRequirement::Any,
209 min_compute_capability: None,
210 cluster: None,
211 cooperative: false,
212 };
213}
214
215pub unsafe trait KernelSignature: 'static {
225 type Arguments<'a>;
227
228 type RawArguments: Copy + 'static;
230
231 const PARAMETERS: &'static [ParameterLayout];
233
234 const REQUIREMENTS: LaunchRequirements;
236
237 fn raw_arguments(
244 arguments: Self::Arguments<'_>,
245 context: &Arc<Context>,
246 ) -> Result<Self::RawArguments>;
247
248 fn encode<R>(arguments: Self::RawArguments, f: impl FnOnce(KernelParameters<'_>) -> R) -> R;
250}
251
252#[derive(Debug, Clone, PartialEq, Eq, Error)]
254#[non_exhaustive]
255pub enum LaunchContractError {
256 #[error("kernel parameter count mismatch (expected {expected}, got {actual})")]
258 ParameterCount {
259 expected: usize,
261 actual: usize,
263 },
264 #[error(
266 "kernel parameter {index} layout mismatch (expected offset {expected_offset}, size {expected_size}; got offset {actual_offset}, size {actual_size})"
267 )]
268 ParameterLayout {
269 index: usize,
271 expected_offset: usize,
273 expected_size: usize,
275 actual_offset: usize,
277 actual_size: usize,
279 },
280 #[error("launch dimensions exceed the kernel's {rank:?} dimensional indexing")]
282 Rank {
283 rank: LaunchRank,
285 },
286 #[error("block dimensions {actual:?} do not satisfy {required:?}")]
288 Block {
289 required: BlockRequirement,
291 actual: Dim3,
293 },
294 #[error("`{name}` exceeds its limit (requested {requested}, limit {limit})")]
296 Limit {
297 name: &'static str,
299 requested: u128,
301 limit: u128,
303 },
304 #[error("dynamic shared memory {actual} does not satisfy {required:?}")]
306 SharedMemory {
307 required: SharedMemoryRequirement,
309 actual: usize,
311 },
312 #[error("compute capability {actual:?} is below {required:?}")]
314 Architecture {
315 required: (u32, u32),
317 actual: (u32, u32),
319 },
320 #[error("cluster dimensions {actual:?} do not satisfy {required:?}")]
322 Cluster {
323 required: Option<Dim3>,
325 actual: Option<Dim3>,
327 },
328 #[error("kernel requires explicit cluster dimensions")]
330 ClusterRequired,
331 #[error("device does not support cluster launches")]
333 ClusterUnsupported,
334 #[error("grid dimensions {grid:?} are incompatible with cluster dimensions {cluster:?}")]
336 ClusterGrid {
337 grid: Dim3,
339 cluster: Dim3,
341 },
342 #[error("cooperative launch is required or unsupported on this device")]
344 Cooperative,
345 #[error("shared-memory mode {mode:?} is unsupported by the current driver")]
347 SharedMemoryModeUnsupported {
348 mode: SharedMemoryMode,
350 },
351 #[error("linear launch coordinates exceed 128 bits")]
353 CoordinateOverflow,
354 #[error("kernel parameter layout overflows the host address space")]
356 ParameterLayoutOverflow,
357}
358
359pub struct PreparedLaunch<K: KernelSignature> {
366 function: KernelFunction,
367 config: LaunchConfig,
368 _signature: PhantomData<fn() -> K>,
369}
370
371impl<K: KernelSignature> fmt::Debug for PreparedLaunch<K> {
372 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
373 f.debug_struct("PreparedLaunch")
374 .field("function", &self.function)
375 .field("config", &self.config)
376 .finish()
377 }
378}
379
380impl<K: KernelSignature> Clone for PreparedLaunch<K> {
381 fn clone(&self) -> Self {
382 Self {
383 function: self.function.clone(),
384 config: self.config.clone(),
385 _signature: PhantomData,
386 }
387 }
388}
389
390impl<K: KernelSignature> PreparedLaunch<K> {
391 pub unsafe fn create(function: &KernelFunction, config: LaunchConfig) -> Result<Self> {
406 validate_parameters::<K>(function)?;
407 validate_requirements(function, &config, K::REQUIREMENTS)?;
408 Ok(Self {
409 function: function.clone(),
410 config,
411 _signature: PhantomData,
412 })
413 }
414
415 #[must_use]
417 pub fn function(&self) -> &KernelFunction {
418 &self.function
419 }
420
421 #[must_use]
423 pub fn config(&self) -> &LaunchConfig {
424 &self.config
425 }
426
427 #[must_use]
429 pub fn context(&self) -> &Arc<Context> {
430 self.function.module().context()
431 }
432
433 pub fn validate_stream(&self, stream: &Stream) -> Result<()> {
439 if stream.context() != self.context() {
440 return Err(CudaError::StreamContextMismatch);
441 }
442 Ok(())
443 }
444
445 pub unsafe fn launch_async(&self, arguments: K::Arguments<'_>, stream: &Stream) -> Result<()> {
458 let arguments = K::raw_arguments(arguments, self.context())?;
459 unsafe { self.launch_encoded(arguments, stream) }
461 }
462
463 pub unsafe fn record(
476 &self,
477 arguments: K::Arguments<'_>,
478 scope: &StreamCaptureScope<'_>,
479 ) -> Result<()> {
480 let arguments = K::raw_arguments(arguments, self.context())?;
481 self.validate_stream(scope.stream())?;
482 scope.retain_module(self.function.module());
483 unsafe { self.launch_encoded(arguments, scope.stream()) }
485 }
486
487 pub unsafe fn add_to_graph(
500 &self,
501 arguments: K::Arguments<'_>,
502 graph: &mut Graph,
503 dependencies: &[GraphNode],
504 ) -> Result<GraphNode> {
505 let arguments = K::raw_arguments(arguments, self.context())?;
506 K::encode(arguments, |params| unsafe {
508 self.function
509 .add_to_graph(graph, dependencies, &self.config, params)
510 })
511 }
512
513 pub unsafe fn set_graph_node_params(
527 &self,
528 arguments: K::Arguments<'_>,
529 executable: &mut ExecutableGraph,
530 node: &GraphNode,
531 ) -> Result<()> {
532 let arguments = K::raw_arguments(arguments, self.context())?;
533 K::encode(arguments, |params| unsafe {
535 self.function
536 .set_graph_node_params(executable, node, self.config.geometry(), params)
537 })
538 }
539
540 unsafe fn launch_encoded(&self, arguments: K::RawArguments, stream: &Stream) -> Result<()> {
543 self.validate_stream(stream)?;
544 K::encode(arguments, |params| unsafe {
546 self.function.launch_async(&self.config, params, stream)
547 })
548 }
549}
550
551impl KernelFunction {
552 pub unsafe fn set_typed_graph_node_params<K: KernelSignature>(
566 &self,
567 executable: &mut ExecutableGraph,
568 node: &GraphNode,
569 geometry: &LaunchGeometry,
570 arguments: K::Arguments<'_>,
571 ) -> Result<()> {
572 let arguments = K::raw_arguments(arguments, self.module().context())?;
573 validate_parameters::<K>(self)?;
574 validate_kernel_geometry(self, geometry, K::REQUIREMENTS)?;
575 K::encode(arguments, |params| unsafe {
577 self.set_graph_node_params(executable, node, geometry, params)
578 })
579 }
580}
581
582fn validate_parameters<K: KernelSignature>(function: &KernelFunction) -> Result<()> {
583 function.module().context().bind()?;
584 let mut count = 0;
585 unsafe {
587 try_ffi!(driver::cuFuncGetParamCount(
588 function.as_raw().as_raw(),
589 &raw mut count
590 ))?;
591 }
592
593 if to_usize(count, "kernel parameter count")? != K::PARAMETERS.len() {
594 return Err(LaunchContractError::ParameterCount {
595 expected: K::PARAMETERS.len(),
596 actual: to_usize(count, "kernel parameter count")?,
597 }
598 .into());
599 }
600
601 let mut expected_offset = 0_usize;
602 for (index, parameter) in K::PARAMETERS.iter().enumerate() {
603 let padding = expected_offset.wrapping_neg() & (parameter.alignment - 1);
604 expected_offset = expected_offset
605 .checked_add(padding)
606 .ok_or(LaunchContractError::ParameterLayoutOverflow)?;
607 let mut offset = 0;
608 let mut size = 0;
609 let native_index = index
610 .try_into()
611 .map_err(|_| CudaError::out_of_range("kernel parameter index"))?;
612 unsafe {
614 try_ffi!(driver::cuFuncGetParamInfo(
615 function.as_raw().as_raw(),
616 native_index,
617 &raw mut offset,
618 &raw mut size
619 ))?;
620 }
621
622 if to_usize(offset, "kernel parameter offset")? != expected_offset
623 || to_usize(size, "kernel parameter size")? != parameter.size
624 {
625 return Err(LaunchContractError::ParameterLayout {
626 index,
627 expected_offset,
628 expected_size: parameter.size,
629 actual_offset: to_usize(offset, "kernel parameter offset")?,
630 actual_size: to_usize(size, "kernel parameter size")?,
631 }
632 .into());
633 }
634
635 expected_offset = expected_offset
636 .checked_add(parameter.size)
637 .ok_or(LaunchContractError::ParameterLayoutOverflow)?;
638 }
639 Ok(())
640}
641
642fn native_limit(value: i32) -> Result<u128> {
644 u128::try_from(value).map_err(|_| CudaError::out_of_range("native launch limit"))
645}
646
647fn check_limit(name: &'static str, requested: u128, limit: u128) -> Result<()> {
648 if requested > limit {
649 return Err(LaunchContractError::Limit {
650 name,
651 requested,
652 limit,
653 }
654 .into());
655 }
656 Ok(())
657}
658
659fn volume(dim: Dim3) -> u128 {
660 u128::from(dim.x) * u128::from(dim.y) * u128::from(dim.z)
661}
662
663fn validate_geometry(
664 function: &KernelFunction,
665 geometry: &LaunchGeometry,
666 required: LaunchRequirements,
667) -> Result<()> {
668 let grid = geometry.grid_dim();
669 let block = geometry.block_dim();
670 match required.rank {
671 LaunchRank::One if grid.y != 1 || grid.z != 1 || block.y != 1 || block.z != 1 => {
672 return Err(LaunchContractError::Rank {
673 rank: required.rank,
674 }
675 .into());
676 }
677 LaunchRank::Two if grid.z != 1 || block.z != 1 => {
678 return Err(LaunchContractError::Rank {
679 rank: required.rank,
680 }
681 .into());
682 }
683 _ => {}
684 }
685
686 match required.block {
687 BlockRequirement::MaxThreads(n) if volume(block) > u128::from(n) => {
688 return Err(LaunchContractError::Block {
689 required: required.block,
690 actual: block,
691 }
692 .into());
693 }
694 BlockRequirement::Exact(dim) if dim != block => {
695 return Err(LaunchContractError::Block {
696 required: required.block,
697 actual: block,
698 }
699 .into());
700 }
701 BlockRequirement::MultipleOf(n)
702 if n == 0 || !volume(block).is_multiple_of(u128::from(n)) =>
703 {
704 return Err(LaunchContractError::Block {
705 required: required.block,
706 actual: block,
707 }
708 .into());
709 }
710 _ => {}
711 }
712
713 let context = function.module().context();
714 let device = context.device();
715 for (g, b, grid_attr, block_attr) in [
716 (
717 grid.x,
718 block.x,
719 DeviceAttribute::MaxGridDimX,
720 DeviceAttribute::MaxBlockDimX,
721 ),
722 (
723 grid.y,
724 block.y,
725 DeviceAttribute::MaxGridDimY,
726 DeviceAttribute::MaxBlockDimY,
727 ),
728 (
729 grid.z,
730 block.z,
731 DeviceAttribute::MaxGridDimZ,
732 DeviceAttribute::MaxBlockDimZ,
733 ),
734 ] {
735 check_limit(
736 "grid dimension",
737 u128::from(g),
738 native_limit(device.attribute(grid_attr)?)?,
739 )?;
740 check_limit(
741 "block dimension",
742 u128::from(b),
743 native_limit(device.attribute(block_attr)?)?,
744 )?;
745 if let Some(width) = required.axis_coordinates {
746 check_limit(
747 "axis coordinate",
748 u128::from(g) * u128::from(b) - 1,
749 width.max(),
750 )?;
751 }
752 }
753
754 if let Some(width) = required.linear_coordinates {
755 check_limit(
756 "linear coordinate",
757 volume(grid)
758 .checked_mul(volume(block))
759 .ok_or(LaunchContractError::CoordinateOverflow)?
760 - 1,
761 width.max(),
762 )?;
763 }
764
765 let threads = volume(block);
766 check_limit(
767 "threads per block",
768 threads,
769 native_limit(device.attribute(DeviceAttribute::MaxThreadsPerBlock)?)?,
770 )?;
771 check_limit(
772 "kernel threads per block",
773 threads,
774 native_limit(function.attribute(FunctionAttribute::MaxThreadsPerBlock)?)?,
775 )?;
776 Ok(())
777}
778
779fn validate_kernel_geometry(
780 function: &KernelFunction,
781 geometry: &LaunchGeometry,
782 required: LaunchRequirements,
783) -> Result<()> {
784 validate_geometry(function, geometry, required)?;
785 let device = function.module().context().device();
786 let shared = geometry.shared_memory_bytes();
787 match required.shared_memory {
788 SharedMemoryRequirement::Range { min, max } if shared < min || shared > max => {
789 return Err(LaunchContractError::SharedMemory {
790 required: required.shared_memory,
791 actual: shared,
792 }
793 .into());
794 }
795 SharedMemoryRequirement::Exact(n) if shared != n => {
796 return Err(LaunchContractError::SharedMemory {
797 required: required.shared_memory,
798 actual: shared,
799 }
800 .into());
801 }
802 SharedMemoryRequirement::AtLeast(n) if shared < n => {
803 return Err(LaunchContractError::SharedMemory {
804 required: required.shared_memory,
805 actual: shared,
806 }
807 .into());
808 }
809 _ => {}
810 }
811
812 if let Some(minimum) = required.min_compute_capability {
813 let actual = (
814 to_u32(
815 device.attribute(DeviceAttribute::ComputeCapabilityMajor)?,
816 "native attribute",
817 )?,
818 to_u32(
819 device.attribute(DeviceAttribute::ComputeCapabilityMinor)?,
820 "native attribute",
821 )?,
822 );
823 if actual < minimum {
824 return Err(LaunchContractError::Architecture {
825 required: minimum,
826 actual,
827 }
828 .into());
829 }
830 }
831 Ok(())
832}
833
834fn validate_requirements(
835 function: &KernelFunction,
836 config: &LaunchConfig,
837 required: LaunchRequirements,
838) -> Result<()> {
839 validate_kernel_geometry(function, config.geometry(), required)?;
840 let context = function.module().context();
841 let device = context.device();
842 let grid = config.grid_dim();
843 let threads = volume(config.block_dim());
844 let shared = config.shared_memory_bytes();
845 check_limit(
846 "dynamic shared memory",
847 shared as u128,
848 dynamic_shared_memory_limit(function, config)?,
849 )?;
850 let mut cluster = None;
851 let mut cooperative = false;
852 for attribute in config.attributes() {
853 match attribute {
854 LaunchAttribute::ClusterDimension(dim) => cluster = Some(*dim),
855 LaunchAttribute::Cooperative(value) => cooperative = *value,
856 _ => {}
857 }
858 }
859
860 let native_cluster = Dim3::new(
861 to_u32(
862 function.attribute(FunctionAttribute::RequiredClusterWidth)?,
863 "native attribute",
864 )?,
865 to_u32(
866 function.attribute(FunctionAttribute::RequiredClusterHeight)?,
867 "native attribute",
868 )?,
869 to_u32(
870 function.attribute(FunctionAttribute::RequiredClusterDepth)?,
871 "native attribute",
872 )?,
873 );
874 let native_cluster = (native_cluster.x != 0 || native_cluster.y != 0 || native_cluster.z != 0)
875 .then_some(native_cluster);
876 if let (Some(actual), Some(native)) = (cluster, native_cluster)
877 && actual != native
878 {
879 return Err(LaunchContractError::Cluster {
880 required: Some(native),
881 actual: Some(actual),
882 }
883 .into());
884 }
885
886 let cluster = cluster.or(native_cluster);
887 if required.cluster.is_some() && cluster != required.cluster {
888 return Err(LaunchContractError::Cluster {
889 required: required.cluster,
890 actual: cluster,
891 }
892 .into());
893 }
894
895 if function.attribute(FunctionAttribute::ClusterSizeMustBeSet)? != 0 && cluster.is_none() {
896 return Err(LaunchContractError::ClusterRequired.into());
897 }
898
899 if let Some(dim) = cluster {
900 if device.attribute(DeviceAttribute::ClusterLaunch)? == 0 {
901 return Err(LaunchContractError::ClusterUnsupported.into());
902 }
903
904 if dim.x == 0
905 || dim.y == 0
906 || dim.z == 0
907 || !grid.x.is_multiple_of(dim.x)
908 || !grid.y.is_multiple_of(dim.y)
909 || !grid.z.is_multiple_of(dim.z)
910 {
911 return Err(LaunchContractError::ClusterGrid { grid, cluster: dim }.into());
912 }
913
914 let limit = function.occupancy_max_potential_cluster_size(config)?;
915 check_limit("cluster blocks", volume(dim), native_limit(limit)?)?;
916 }
917
918 if required.cooperative && !cooperative
919 || cooperative && device.attribute(DeviceAttribute::CooperativeLaunch)? == 0
920 {
921 return Err(LaunchContractError::Cooperative.into());
922 }
923
924 if let (true, Some(cluster)) = (cooperative, cluster) {
925 let active = function.occupancy_max_active_clusters(config)?;
926 check_limit(
927 "cooperative grid clusters",
928 volume(grid) / volume(cluster),
929 native_limit(active)?,
930 )?;
931 } else if cooperative {
932 let active = function.occupancy_max_active_blocks_per_multiprocessor(
933 to_i32(threads, "block thread count")?,
934 shared,
935 OccupancyFlags::DEFAULT,
936 )?;
937 let sms = SmResource::for_context(context)?.sm_count();
938 check_limit(
939 "cooperative grid blocks",
940 volume(grid),
941 native_limit(active)? * u128::from(sms),
942 )?;
943 }
944 Ok(())
945}
946
947fn dynamic_shared_memory_limit(function: &KernelFunction, config: &LaunchConfig) -> Result<u128> {
948 let requested = config.attributes().iter().find_map(|attribute| {
949 if let LaunchAttribute::SharedMemoryMode(mode) = attribute {
950 Some(*mode)
951 } else {
952 None
953 }
954 });
955 let function_mode = match function.shared_memory_mode() {
956 Ok(mode) => mode,
957 Err(CudaError::Cuda {
960 code: Status::InvalidValue | Status::NotSupported,
961 ..
962 }) => match requested {
963 None => SharedMemoryMode::Default,
964 Some(mode) => {
965 return Err(LaunchContractError::SharedMemoryModeUnsupported { mode }.into());
966 }
967 },
968 Err(error) => return Err(error),
969 };
970 let mode = requested.unwrap_or(function_mode);
971 let device = function.module().context().device();
972 let capacity = match mode {
973 SharedMemoryMode::Default => {
974 return native_limit(function.attribute(FunctionAttribute::MaxDynamicSharedSizeBytes)?);
975 }
976 SharedMemoryMode::RequirePortable => {
977 native_limit(device.attribute(DeviceAttribute::MaxSharedMemoryPerBlock)?)?
978 }
979 SharedMemoryMode::AllowNonPortable => {
980 native_limit(device.attribute(DeviceAttribute::MaxSharedMemoryPerBlockOptin)?)?
981 }
982 SharedMemoryMode::AllowOversizedSharedMemory
983 | SharedMemoryMode::PreferOversizedSharedMemory => {
984 let optin = device.attribute(DeviceAttribute::MaxSharedMemoryPerBlockOptin)?;
985 let oversized = device.attribute(DeviceAttribute::MaxOversizedSharedMemoryPerBlock)?;
986 native_limit(optin.max(oversized))?
987 }
988 };
989 let static_bytes = native_limit(function.attribute(FunctionAttribute::SharedSizeBytes)?)?;
990 check_limit("static shared memory", static_bytes, capacity)?;
991 Ok(capacity - static_bytes)
992}
993
994#[derive(Debug)]
996pub struct KernelOperation<K: KernelSignature, T> {
997 launch: PreparedLaunch<K>,
998 arguments: K::RawArguments,
999 resources: Resources,
1000 output: T,
1001}
1002
1003impl<K: KernelSignature> PreparedLaunch<K> {
1004 pub unsafe fn into_operation<T: 'static>(
1016 self,
1017 arguments: K::Arguments<'_>,
1018 mut resources: Resources,
1019 output: T,
1020 ) -> Result<KernelOperation<K, T>> {
1021 let arguments = K::raw_arguments(arguments, self.context())?;
1022 resources.retain(Arc::new(self.function.module().clone()));
1023 Ok(KernelOperation {
1024 launch: self,
1025 arguments,
1026 resources,
1027 output,
1028 })
1029 }
1030}
1031
1032unsafe impl<K: KernelSignature, T: 'static> Operation for KernelOperation<K, T> {
1034 type Pending = Self::Output;
1035
1036 type Output = T;
1037
1038 fn enqueue(self, execution: &mut Execution) -> Result<T> {
1039 unsafe {
1041 execution.enqueue(self.resources, |stream| {
1042 self.launch.launch_encoded(self.arguments, stream)
1043 })?;
1044 }
1045 Ok(self.output)
1046 }
1047
1048 unsafe fn resolve(pending: Self::Pending) -> Result<Self::Output> {
1049 Ok(pending)
1050 }
1051}
1052
1053unsafe impl<K: KernelSignature, T: 'static> DeviceOperation for KernelOperation<K, T> {}
1055
1056unsafe impl<K: KernelSignature, T: 'static> Recordable for KernelOperation<K, T> {
1058 type Output = T;
1059
1060 fn record(self, recording: &mut Recording) -> Result<T> {
1061 unsafe {
1063 recording.enqueue(self.resources, |stream| {
1064 self.launch.launch_encoded(self.arguments, stream)
1065 })?;
1066 }
1067 Ok(self.output)
1068 }
1069}