cudarc 0.19.4

Safe and minimal CUDA bindings
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
use std::vec::Vec;

use crate::driver::{
    result::{self, DriverError},
    sys,
};

use super::{CudaEvent, CudaFunction, CudaSlice, CudaStream, CudaView, CudaViewMut, DeviceRepr};

/// Configuration for [result::launch_kernel]
///
/// See [cuda docs](https://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__EXEC.html#group__CUDA__EXEC_1gb8f3dc3031b40da29d5f9a7139e52e15)
/// for description of each parameter.
#[derive(Clone, Copy, Debug)]
pub struct LaunchConfig {
    /// (width, height, depth) of grid in blocks
    pub grid_dim: (u32, u32, u32),

    /// (x, y, z) dimension of each thread block
    pub block_dim: (u32, u32, u32),

    /// Dynamic shared-memory size per thread block in bytes
    pub shared_mem_bytes: u32,
}

impl LaunchConfig {
    /// Creates a [LaunchConfig] with:
    /// - block_dim == `1024`
    /// - grid_dim == `(n + 1023) / 1024`
    /// - shared_mem_bytes == `0`
    pub fn for_num_elems(n: u32) -> Self {
        const NUM_THREADS: u32 = 1024;
        let num_blocks = n.div_ceil(NUM_THREADS);
        Self {
            grid_dim: (num_blocks, 1, 1),
            block_dim: (NUM_THREADS, 1, 1),
            shared_mem_bytes: 0,
        }
    }
}

/// The kernel launch builder. Instantiate with [CudaStream::launch_builder()], and then
/// launch the kernel with [LaunchArgs::launch()]
///
/// Anything added as a kernel argument with [LaunchArgs::arg()] must either:
/// 1. Implement [DeviceRepr]
/// 2. Add a custom implementation of `impl<'a> PushKernelArg<T> for LaunchArgs<'a>`, where `T` is your type.
#[derive(Debug)]
pub struct LaunchArgs<'a> {
    pub(super) stream: &'a CudaStream,
    pub(super) func: &'a CudaFunction,
    pub(super) waits: Vec<&'a CudaEvent>,
    pub(super) records: Vec<&'a CudaEvent>,
    pub(super) args: Vec<*mut std::ffi::c_void>,
    pub(super) flags: Option<sys::CUevent_flags>,
}

impl CudaStream {
    /// Creates a new kernel launch builder that will launch `func` on stream `self`.
    ///
    /// Add arguments to the builder using [LaunchArgs::arg()], and submit it to the stream
    /// using [LaunchArgs::launch()].
    pub fn launch_builder<'a>(&'a self, func: &'a CudaFunction) -> LaunchArgs<'a> {
        LaunchArgs {
            stream: self,
            func,
            waits: Vec::new(),
            records: Vec::new(),
            args: Vec::new(),
            flags: None,
        }
    }
}

/// Something that can be copied to device memory and
/// turned into a parameter for [result::launch_kernel].
///
/// See the [cuda docs](https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#global-function-argument-processing)
/// on argument processing.
///
/// # Safety
///
/// This is unsafe you need to ensure that T can be represented
/// in CUDA and also references to it can be properly passed to CUDA.
///
/// Most implementations will be required to use `#[inline(always)]`
/// to ensure that references are handled properly.
pub unsafe trait PushKernelArg<T> {
    fn arg(&mut self, arg: T) -> &mut Self;
}

unsafe impl<'a, 'b: 'a, T: DeviceRepr> PushKernelArg<&'b T> for LaunchArgs<'a> {
    #[inline(always)]
    fn arg(&mut self, arg: &'b T) -> &mut Self {
        self.args.push(arg as *const T as *mut _);
        self
    }
}

unsafe impl<'a, 'b: 'a, T> PushKernelArg<&'b CudaSlice<T>> for LaunchArgs<'a> {
    #[inline(always)]
    fn arg(&mut self, arg: &'b CudaSlice<T>) -> &mut Self {
        if self.stream.context().is_managing_stream_synchronization() {
            if let Some(write) = arg.write.as_ref() {
                self.waits.push(write);
            }
            if let Some(read) = arg.read.as_ref() {
                self.records.push(read);
            }
        }
        self.args
            .push((&arg.cu_device_ptr) as *const sys::CUdeviceptr as _);
        self
    }
}

unsafe impl<'a, 'b: 'a, T> PushKernelArg<&'b mut CudaSlice<T>> for LaunchArgs<'a> {
    #[inline(always)]
    fn arg(&mut self, arg: &'b mut CudaSlice<T>) -> &mut Self {
        if self.stream.context().is_managing_stream_synchronization() {
            if let Some(read) = arg.read.as_ref() {
                self.waits.push(read);
            }
            if let Some(write) = arg.write.as_ref() {
                self.waits.push(write);
                self.records.push(write);
            }
        }
        self.args
            .push((&arg.cu_device_ptr) as *const sys::CUdeviceptr as _);
        self
    }
}

unsafe impl<'a, 'b: 'a, 'c: 'b, T> PushKernelArg<&'b CudaView<'c, T>> for LaunchArgs<'a> {
    #[inline(always)]
    fn arg(&mut self, arg: &'b CudaView<'c, T>) -> &mut Self {
        if self.stream.context().is_managing_stream_synchronization() {
            if let Some(write) = arg.write.as_ref() {
                self.waits.push(write);
            }
            if let Some(read) = arg.read.as_ref() {
                self.records.push(read);
            }
        }
        self.args.push((&arg.ptr) as *const sys::CUdeviceptr as _);
        self
    }
}

unsafe impl<'a, 'b: 'a, 'c: 'b, T> PushKernelArg<&'b mut CudaViewMut<'c, T>> for LaunchArgs<'a> {
    #[inline(always)]
    fn arg(&mut self, arg: &'b mut CudaViewMut<'c, T>) -> &mut Self {
        if self.stream.context().is_managing_stream_synchronization() {
            if let Some(read) = arg.read.as_ref() {
                self.waits.push(read);
            }
            if let Some(write) = arg.write.as_ref() {
                self.waits.push(write);
                self.records.push(write);
            }
        }
        self.args.push((&arg.ptr) as *const sys::CUdeviceptr as _);
        self
    }
}

impl LaunchArgs<'_> {
    /// Calling this will make [LaunchArgs::launch()] and [LaunchArgs::launch_cooperative()]
    /// return 2 [CudaEvent]s that recorded before and after the kernel is submitted.
    pub fn record_kernel_launch(&mut self, flags: sys::CUevent_flags) -> &mut Self {
        self.flags = Some(flags);
        self
    }

    /// Submits the configuration [CudaFunction] to execute asychronously on
    /// the configured device stream.
    ///
    /// # Safety
    ///
    /// This is generally unsafe for two main reasons:
    ///
    /// 1. We can't guarantee that the arguments are valid for the configured [CudaFunction].
    ///    We don't know if the types are correct, if the arguments are in the correct order,
    ///    if the types are representable in CUDA, etc.
    /// 2. We can't guarantee that the cuda kernel follows the mutability of the arguments
    ///    configured with [LaunchArgs::arg()]. For instance, you can pass a reference to a [CudaSlice],
    ///    which on rust side can't be mutated, but on cuda side the kernel can mutate it.
    /// 3. [CudaFunction] can access memory outside of limits.
    ///
    /// ## Handling asynchronous mutation
    ///
    /// All [CudaSlice]/[CudaView]/[CudaViewMut] contain 2 events that record
    /// when the data associated with them are read from/written to.
    ///
    /// The [PushKernelArg] implementation of these adds these events to [LaunchArgs],
    /// so when [LaunchArgs::launch()] is called, we properly do multi stream synchronization.
    ///
    /// So in practice it is not possible to have multiple kernels concurrently modify device
    /// data while using the safe api.
    ///
    /// ## Handling use after free
    ///
    /// Since [LaunchArgs::launch()] properly records reads/writes for [CudaSlice]/[CudaView]/[CudaViewMut],
    /// and the drop implementation of [CudaSlice] waits on those events to finish,
    /// we will never encounter a use after free situation.
    #[inline(always)]
    pub unsafe fn launch(
        &mut self,
        cfg: LaunchConfig,
    ) -> Result<Option<(CudaEvent, CudaEvent)>, DriverError> {
        self.stream.ctx.bind_to_thread()?;
        for &event in self.waits.iter() {
            self.stream.wait(event)?;
        }
        let start_event = self
            .flags
            .map(|flags| self.stream.record_event(Some(flags)))
            .transpose()?;
        result::launch_kernel(
            self.func.cu_function,
            cfg.grid_dim,
            cfg.block_dim,
            cfg.shared_mem_bytes,
            self.stream.cu_stream,
            &mut self.args,
        )?;
        let end_event = self
            .flags
            .map(|flags| self.stream.record_event(Some(flags)))
            .transpose()?;
        for &event in self.records.iter() {
            event.record(self.stream)?;
        }
        Ok(start_event.zip(end_event))
    }

    /// Launch a cooperative kernel.
    ///
    /// # Safety
    /// See [LaunchArgs::launch()]
    #[inline(always)]
    pub unsafe fn launch_cooperative(
        &mut self,
        cfg: LaunchConfig,
    ) -> Result<Option<(CudaEvent, CudaEvent)>, DriverError> {
        self.stream.ctx.bind_to_thread()?;
        for &event in self.waits.iter() {
            self.stream.wait(event)?;
        }
        let start_event = self
            .flags
            .map(|flags| self.stream.record_event(Some(flags)))
            .transpose()?;
        result::launch_cooperative_kernel(
            self.func.cu_function,
            cfg.grid_dim,
            cfg.block_dim,
            cfg.shared_mem_bytes,
            self.stream.cu_stream,
            &mut self.args,
        )?;
        let end_event = self
            .flags
            .map(|flags| self.stream.record_event(Some(flags)))
            .transpose()?;
        for &event in self.records.iter() {
            event.record(self.stream)?;
        }
        Ok(start_event.zip(end_event))
    }
}

#[cfg(test)]
mod tests {
    use crate::driver::{CudaContext, DriverError};
    #[cfg(feature = "nvrtc")]
    use crate::nvrtc::compile_ptx_with_opts;

    use super::*;

    #[cfg(feature = "nvrtc")]
    #[test]
    fn test_launch_arrays() -> Result<(), DriverError> {
        #[repr(C)]
        struct TensorMeta {
            num_dims: usize,
            strides: [usize; 128],
            shape: [usize; 128],
        }
        unsafe impl DeviceRepr for TensorMeta {}

        let ctx = CudaContext::new(0).unwrap();
        let stream = ctx.default_stream();

        let ptx = compile_ptx_with_opts(
            "
struct TensorMeta {
    size_t num_dims;
    size_t shape[128];
    size_t strides[128];
};

extern \"C\" __global__ void kernel(const TensorMeta meta) {
    for (int i = 0;i < meta.num_dims;i++) {
        assert(meta.shape[i] == i);
        assert(meta.strides[i] == i);
    }
}
        ",
            Default::default(),
        )
        .unwrap();

        let module = ctx.load_module(ptx).unwrap();
        let f = module.load_function("kernel").unwrap();

        let meta = TensorMeta {
            num_dims: 128,
            shape: std::array::from_fn(|i| i),
            strides: std::array::from_fn(|i| i),
        };

        unsafe {
            stream
                .launch_builder(&f)
                .arg(&meta)
                .launch(LaunchConfig::for_num_elems(1))
        }?;

        stream.synchronize()?;

        Ok(())
    }

    const SIN_CU: &str = "
extern \"C\" __global__ void sin_kernel(float *out, const float *inp, size_t numel) {
    size_t i = blockIdx.x * blockDim.x + threadIdx.x;
    if (i < numel) {
        out[i] = sin(inp[i]);
    }
}";

    #[cfg(feature = "nvrtc")]
    #[test]
    fn test_launch_with_mut_and_ref_cudarc() {
        let ctx = CudaContext::new(0).unwrap();
        let stream = ctx.default_stream();

        let ptx = compile_ptx_with_opts(SIN_CU, Default::default()).unwrap();
        let module = ctx.load_module(ptx).unwrap();
        let sin_kernel = module.load_function("sin_kernel").unwrap();

        let a_host = [-1.0f32, -0.8, -0.6, -0.4, -0.2, 0.0, 0.2, 0.4, 0.6, 0.8];

        let a_dev = stream.clone_htod(&a_host).unwrap();
        let mut b_dev = a_dev.clone();

        unsafe {
            stream
                .launch_builder(&sin_kernel)
                .arg(&mut b_dev)
                .arg(&a_dev)
                .arg(&10usize)
                .launch(LaunchConfig::for_num_elems(10))
        }
        .unwrap();

        let b_host = stream.clone_dtoh(&b_dev).unwrap();

        for (a_i, b_i) in a_host.iter().zip(b_host.iter()) {
            let expected = a_i.sin();
            assert!((b_i - expected).abs() <= 1e-6);
        }

        drop(a_dev);
    }

    #[cfg(feature = "nvrtc")]
    #[test]
    fn test_large_launches() {
        let ctx = CudaContext::new(0).unwrap();
        let stream = ctx.default_stream();

        let ptx = compile_ptx_with_opts(SIN_CU, Default::default()).unwrap();
        let module = ctx.load_module(ptx).unwrap();
        let sin_kernel = module.load_function("sin_kernel").unwrap();

        for numel in [256, 512, 1024, 1280, 1536, 2048] {
            let mut a = Vec::with_capacity(numel);
            a.resize(numel, 1.0f32);

            let a = stream.clone_htod(&a).unwrap();
            let mut b = stream.alloc_zeros::<f32>(numel).unwrap();
            unsafe {
                stream
                    .launch_builder(&sin_kernel)
                    .arg(&mut b)
                    .arg(&a)
                    .arg(&numel)
                    .launch(LaunchConfig::for_num_elems(numel as u32))
            }
            .unwrap();

            let b = stream.clone_dtoh(&b).unwrap();
            for v in b {
                assert_eq!(v, 0.841471);
            }
        }
    }

    #[cfg(feature = "nvrtc")]
    #[test]
    fn test_launch_with_views() {
        let ctx = CudaContext::new(0).unwrap();
        let stream = ctx.default_stream();

        let ptx = compile_ptx_with_opts(SIN_CU, Default::default()).unwrap();
        let module = ctx.load_module(ptx).unwrap();
        let f = module.load_function("sin_kernel").unwrap();

        let a_host = [-1.0f32, -0.8, -0.6, -0.4, -0.2, 0.0, 0.2, 0.4, 0.6, 0.8];
        let a_dev = stream.clone_htod(&a_host).unwrap();
        let mut b_dev = a_dev.clone();

        for i in 0..5 {
            let a_sub = a_dev.try_slice(i * 2..).unwrap();
            assert_eq!(a_sub.len, 10 - 2 * i);
            let mut b_sub = b_dev.try_slice_mut(i * 2..).unwrap();
            assert_eq!(b_sub.len, 10 - 2 * i);
            unsafe {
                stream
                    .launch_builder(&f)
                    .arg(&mut b_sub)
                    .arg(&a_sub)
                    .arg(&2usize)
                    .launch(LaunchConfig::for_num_elems(2))
            }
            .unwrap();
        }

        let b_host = stream.clone_dtoh(&b_dev).unwrap();

        for (a_i, b_i) in a_host.iter().zip(b_host.iter()) {
            let expected = a_i.sin();
            assert!((b_i - expected).abs() <= 1e-6);
        }

        drop(a_dev);
    }

    const TEST_KERNELS: &str = "
extern \"C\" __global__ void int_8bit(signed char s_min, char s_max, unsigned char u_min, unsigned char u_max) {
    assert(s_min == -128);
    assert(s_max == 127);
    assert(u_min == 0);
    assert(u_max == 255);
}

extern \"C\" __global__ void int_16bit(signed short s_min, short s_max, unsigned short u_min, unsigned short u_max) {
    assert(s_min == -32768);
    assert(s_max == 32767);
    assert(u_min == 0);
    assert(u_max == 65535);
}

extern \"C\" __global__ void int_32bit(signed int s_min, int s_max, unsigned int u_min, unsigned int u_max) {
    assert(s_min == -2147483648);
    assert(s_max == 2147483647);
    assert(u_min == 0);
    assert(u_max == 4294967295);
}

extern \"C\" __global__ void int_64bit(signed long s_min, long s_max, unsigned long u_min, unsigned long u_max) {
    assert(s_min == -9223372036854775808);
    assert(s_max == 9223372036854775807);
    assert(u_min == 0);
    assert(u_max == 18446744073709551615);
}

extern \"C\" __global__ void floating(float f, double d) {
    assert(fabs(f - 1.2345678) <= 1e-7);
    assert(fabs(d - -10.123456789876543) <= 1e-16);
}
";

    #[cfg(feature = "nvrtc")]
    #[test]
    fn test_launch_with_8bit() {
        let ctx = CudaContext::new(0).unwrap();
        let stream = ctx.default_stream();
        let ptx = compile_ptx_with_opts(TEST_KERNELS, Default::default()).unwrap();
        let module = ctx.load_module(ptx).unwrap();
        let f = module.load_function("int_8bit").unwrap();
        unsafe {
            stream
                .launch_builder(&f)
                .arg(&i8::MIN)
                .arg(&i8::MAX)
                .arg(&u8::MIN)
                .arg(&u8::MAX)
                .launch(LaunchConfig::for_num_elems(1))
        }
        .unwrap();
        stream.synchronize().unwrap();
    }

    #[cfg(feature = "nvrtc")]
    #[test]
    fn test_launch_with_16bit() {
        let ctx = CudaContext::new(0).unwrap();
        let stream = ctx.default_stream();
        let ptx = compile_ptx_with_opts(TEST_KERNELS, Default::default()).unwrap();
        let module = ctx.load_module(ptx).unwrap();
        let f = module.load_function("int_16bit").unwrap();
        unsafe {
            stream
                .launch_builder(&f)
                .arg(&i16::MIN)
                .arg(&i16::MAX)
                .arg(&u16::MIN)
                .arg(&u16::MAX)
                .launch(LaunchConfig::for_num_elems(1))
        }
        .unwrap();
        stream.synchronize().unwrap();
    }

    #[cfg(feature = "nvrtc")]
    #[test]
    fn test_launch_with_32bit() {
        let ctx = CudaContext::new(0).unwrap();
        let stream = ctx.default_stream();
        let ptx = compile_ptx_with_opts(TEST_KERNELS, Default::default()).unwrap();
        let module = ctx.load_module(ptx).unwrap();
        let f = module.load_function("int_32bit").unwrap();
        unsafe {
            stream
                .launch_builder(&f)
                .arg(&i32::MIN)
                .arg(&i32::MAX)
                .arg(&u32::MIN)
                .arg(&u32::MAX)
                .launch(LaunchConfig::for_num_elems(1))
        }
        .unwrap();
        stream.synchronize().unwrap();
    }

    #[cfg(feature = "nvrtc")]
    #[test]
    fn test_launch_with_64bit() {
        let ctx = CudaContext::new(0).unwrap();
        let stream = ctx.default_stream();
        let ptx = compile_ptx_with_opts(TEST_KERNELS, Default::default()).unwrap();
        let module = ctx.load_module(ptx).unwrap();
        let f = module.load_function("int_64bit").unwrap();
        unsafe {
            stream
                .launch_builder(&f)
                .arg(&i64::MIN)
                .arg(&i64::MAX)
                .arg(&u64::MIN)
                .arg(&u64::MAX)
                .launch(LaunchConfig::for_num_elems(1))
        }
        .unwrap();
        stream.synchronize().unwrap();
    }

    #[cfg(feature = "nvrtc")]
    #[test]
    fn test_launch_with_floats() {
        let ctx = CudaContext::new(0).unwrap();
        let stream = ctx.default_stream();
        let ptx = compile_ptx_with_opts(TEST_KERNELS, Default::default()).unwrap();
        let module = ctx.load_module(ptx).unwrap();
        let f = module.load_function("floating").unwrap();
        unsafe {
            stream
                .launch_builder(&f)
                .arg(&1.2345678f32)
                .arg(&-10.123456789876543f64)
                .launch(LaunchConfig::for_num_elems(1))
        }
        .unwrap();
        stream.synchronize().unwrap();
    }

    #[cfg(feature = "f16")]
    const HALF_KERNELS: &str = "
#include \"cuda_fp16.h\"

extern \"C\" __global__ void halfs(__half h) {
    assert(__habs(h - __float2half(1.234)) <= __float2half(1e-4));
}
";

    #[cfg(feature = "f16")]
    #[test]
    fn test_launch_with_half() {
        use crate::nvrtc::CompileOptions;

        let ptx = compile_ptx_with_opts(
            HALF_KERNELS,
            CompileOptions {
                include_paths: std::vec!["/usr/include".into()],
                arch: Some("compute_53"),
                ..Default::default()
            },
        )
        .unwrap();
        let ctx = CudaContext::new(0).unwrap();
        let stream = ctx.default_stream();
        let module = ctx.load_module(ptx).unwrap();
        let f = module.load_function("halfs").unwrap();
        unsafe {
            stream
                .launch_builder(&f)
                .arg(&half::f16::from_f32(1.234))
                .launch(LaunchConfig::for_num_elems(1))
        }
        .unwrap();
        stream.synchronize().unwrap();
    }

    const SLOW_KERNELS: &str = "
extern \"C\" __global__ void slow_worker(const float *data, const size_t len, float *out) {
    float tmp = 0.0;
    for(size_t i = 0; i < 1000000; i++) {
        tmp += data[i % len];
    }
    *out = tmp;
}
";

    #[cfg(feature = "nvrtc")]
    #[test]
    fn test_par_launch() -> Result<(), DriverError> {
        let ptx = compile_ptx_with_opts(SLOW_KERNELS, Default::default()).unwrap();
        let ctx = CudaContext::new(0)?;
        let module = ctx.load_module(ptx).unwrap();
        let f = module.load_function("slow_worker").unwrap();

        let stream = ctx.new_stream()?;
        let slice = stream.alloc_zeros::<f32>(1000)?;
        let mut a = stream.alloc_zeros::<f32>(1)?;
        let mut b = stream.alloc_zeros::<f32>(1)?;
        stream.synchronize()?;

        let cfg = LaunchConfig::for_num_elems(1);

        let double_launch_ms = {
            // launch two kernels on the default stream
            let start = stream.record_event(Some(sys::CUevent_flags::CU_EVENT_DEFAULT))?;
            unsafe {
                stream
                    .launch_builder(&f)
                    .arg(&slice)
                    .arg(&slice.len())
                    .arg(&mut a)
                    .launch(cfg)?
            };
            unsafe {
                stream
                    .launch_builder(&f)
                    .arg(&slice)
                    .arg(&slice.len())
                    .arg(&mut b)
                    .launch(cfg)?
            };
            let end = stream.record_event(Some(sys::CUevent_flags::CU_EVENT_DEFAULT))?;
            stream.synchronize()?;
            start.elapsed_ms(&end)?
        };

        let stream2 = stream.fork()?;
        let par_launch_ms = {
            // create a new stream & launch them concurrently
            let start = stream.record_event(Some(sys::CUevent_flags::CU_EVENT_DEFAULT))?;
            unsafe {
                stream
                    .launch_builder(&f)
                    .arg(&slice)
                    .arg(&slice.len())
                    .arg(&mut a)
                    .launch(cfg)?
            };
            unsafe {
                stream2
                    .launch_builder(&f)
                    .arg(&slice)
                    .arg(&slice.len())
                    .arg(&mut b)
                    .launch(cfg)?
            };
            stream.join(&stream2)?;
            let end = stream.record_event(Some(sys::CUevent_flags::CU_EVENT_DEFAULT))?;
            stream.synchronize()?;
            start.elapsed_ms(&end)?
        };

        assert!(
            (double_launch_ms - 2.0 * par_launch_ms).abs() < 0.2 * double_launch_ms,
            "par={par_launch_ms:?} dbl={double_launch_ms:?}"
        );
        Ok(())
    }

    #[cfg(feature = "nvrtc")]
    #[test]
    fn test_multi_stream_concurrent_reads() -> Result<(), DriverError> {
        let ptx = compile_ptx_with_opts(SLOW_KERNELS, Default::default()).unwrap();
        let ctx = CudaContext::new(0)?;
        let module = ctx.load_module(ptx)?;
        let f = module.load_function("slow_worker")?;

        let stream1 = ctx.new_stream()?;

        let src = stream1.alloc_zeros::<f32>(1000)?;
        let numel = src.len();
        let mut dst1 = stream1.alloc_zeros::<f32>(1)?;
        let mut dst2 = stream1.alloc_zeros::<f32>(1)?;

        let stream2 = stream1.fork()?;

        let cfg = LaunchConfig::for_num_elems(1);

        let mut builder = stream1.launch_builder(&f);
        builder
            .arg(&src)
            .arg(&numel)
            .arg(&mut dst1)
            .record_kernel_launch(sys::CUevent_flags::CU_EVENT_DEFAULT);
        let (_, stream1_finish) = unsafe { builder.launch(cfg) }?.unwrap();

        let mut builder = stream2.launch_builder(&f);
        builder
            .arg(&src)
            .arg(&numel)
            .arg(&mut dst2)
            .record_kernel_launch(sys::CUevent_flags::CU_EVENT_DEFAULT);
        let (stream2_start, _) = unsafe { builder.launch(cfg) }?.unwrap();

        stream1.synchronize()?;
        stream2.synchronize()?;

        assert!(stream2_start.elapsed_ms(&stream1_finish)? >= 0.0);
        Ok(())
    }

    #[cfg(feature = "nvrtc")]
    #[test]
    fn test_multi_stream_writes_block() -> Result<(), DriverError> {
        let ptx = compile_ptx_with_opts(SLOW_KERNELS, Default::default()).unwrap();
        let ctx = CudaContext::new(0)?;
        let module = ctx.load_module(ptx)?;
        let f = module.load_function("slow_worker")?;

        let stream1 = ctx.new_stream()?;

        let src = stream1.alloc_zeros::<f32>(1000)?;
        let numel = src.len();
        let mut dst = stream1.alloc_zeros::<f32>(1)?;
        let cfg = LaunchConfig::for_num_elems(1);

        let stream2 = stream1.fork()?;

        let mut builder = stream1.launch_builder(&f);
        builder
            .arg(&src)
            .arg(&numel)
            .arg(&mut dst)
            .record_kernel_launch(sys::CUevent_flags::CU_EVENT_DEFAULT);
        let (_, stream1_finish) = unsafe { builder.launch(cfg) }?.unwrap();

        let mut builder = stream2.launch_builder(&f);
        builder
            .arg(&src)
            .arg(&numel)
            .arg(&mut dst)
            .record_kernel_launch(sys::CUevent_flags::CU_EVENT_DEFAULT);
        let (stream2_start, _) = unsafe { builder.launch(cfg) }?.unwrap();

        stream1.synchronize()?;
        stream2.synchronize()?;

        assert!(stream1_finish.elapsed_ms(&stream2_start)? >= 0.0);
        Ok(())
    }

    #[cfg(feature = "nvrtc")]
    #[test]
    #[ignore = "must be executed by itself"]
    fn test_device_side_assert() -> Result<(), DriverError> {
        let ctx = CudaContext::new(0)?;
        let stream = ctx.new_stream()?;
        let inp = stream.clone_htod(&[1.0f32; 100])?;
        let mut out = stream.alloc_zeros::<f32>(100)?;
        let ptx = crate::nvrtc::compile_ptx(
            "
    extern \"C\" __global__ void foo(float *out, const float *inp, const size_t numel) {
        assert(0);
    }",
        )
        .unwrap();
        let module = ctx.load_module(ptx)?;
        let foo = module.load_function("foo")?;
        let mut builder = stream.launch_builder(&foo);
        builder.arg(&mut out);
        builder.arg(&inp);
        builder.arg(&100usize);
        unsafe { builder.launch(LaunchConfig::for_num_elems(100)) }?;
        std::thread::sleep(std::time::Duration::from_secs(1));
        stream
            .synchronize()
            .expect_err("Should've had device side assert");
        Ok(())
    }
}