vyre-driver-cuda 0.6.1

CUDA/PTX backend for vyre through the CUDA driver API.
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
//! Shared checked CUDA copy primitives.
//!
//! All CUDA host-to-device upload paths should pass through this module so
//! stream choice, zero-byte behavior, telemetry hooks, and future batched-copy
//! instrumentation live behind one boundary instead of repeated FFI blocks.

use std::ffi::c_void;

use cudarc::driver::sys::CUstream;
use vyre_driver::BackendError;

use super::allocations::cuda_check;

pub(crate) const CUDA_ASYNC_COPY_ALIGNMENT: usize = 16;

pub(crate) fn aligned_async_copy_len(byte_len: usize) -> Result<usize, BackendError> {
    if byte_len == 0 {
        return Ok(0);
    }
    byte_len
        .checked_add(CUDA_ASYNC_COPY_ALIGNMENT - 1)
        .map(|len| len & !(CUDA_ASYNC_COPY_ALIGNMENT - 1))
        .ok_or_else(|| BackendError::InvalidProgram {
            fix: format!(
                "Fix: CUDA async transfer length {byte_len} cannot be rounded to {CUDA_ASYNC_COPY_ALIGNMENT}-byte alignment without overflowing usize."
            ),
        })
}

fn validate_nonzero_host_to_device_copy(
    dst: u64,
    src: *const c_void,
    stream: CUstream,
    label: &'static str,
) -> Result<(), BackendError> {
    if dst == 0 {
        return Err(BackendError::InvalidProgram {
            fix: format!(
                "Fix: {label} received a null CUDA device destination for a non-zero host-to-device copy. Preserve descriptor ordering and allocate device storage before enqueueing the copy."
            ),
        });
    }
    if src.is_null() {
        return Err(BackendError::InvalidProgram {
            fix: format!(
                "Fix: {label} received a null host source for a non-zero host-to-device copy. Keep the pinned host staging allocation alive until the CUDA stream completes."
            ),
        });
    }
    if stream.is_null() {
        return Err(BackendError::InvalidProgram {
            fix: format!(
                "Fix: {label} received a null CUDA stream for a non-zero host-to-device copy. Use a backend-owned stream instead of the legacy default stream."
            ),
        });
    }
    Ok(())
}

fn validate_nonzero_device_to_host_copy(
    dst: *mut c_void,
    src: u64,
    stream: CUstream,
    label: &'static str,
) -> Result<(), BackendError> {
    if dst.is_null() {
        return Err(BackendError::InvalidProgram {
            fix: format!(
                "Fix: {label} received a null host destination for a non-zero device-to-host copy. Allocate pinned host readback storage before enqueueing the copy."
            ),
        });
    }
    if src == 0 {
        return Err(BackendError::InvalidProgram {
            fix: format!(
                "Fix: {label} received a null CUDA device source for a non-zero device-to-host copy. Preserve output descriptor ordering and allocate device storage before readback."
            ),
        });
    }
    if stream.is_null() {
        return Err(BackendError::InvalidProgram {
            fix: format!(
                "Fix: {label} received a null CUDA stream for a non-zero device-to-host copy. Use a backend-owned stream instead of the legacy default stream."
            ),
        });
    }
    Ok(())
}

fn validate_nonzero_sync_device_to_host_copy(
    dst: *mut c_void,
    src: u64,
    label: &'static str,
) -> Result<(), BackendError> {
    if dst.is_null() {
        return Err(BackendError::InvalidProgram {
            fix: format!(
                "Fix: {label} received a null host destination for a non-zero synchronous device-to-host copy. Allocate readback storage before copying."
            ),
        });
    }
    if src == 0 {
        return Err(BackendError::InvalidProgram {
            fix: format!(
                "Fix: {label} received a null CUDA device source for a non-zero synchronous device-to-host copy. Preserve output descriptor ordering and allocate device storage before readback."
            ),
        });
    }
    Ok(())
}

fn validate_nonzero_device_memset(
    dst: u64,
    stream: CUstream,
    label: &'static str,
) -> Result<(), BackendError> {
    if dst == 0 {
        return Err(BackendError::InvalidProgram {
            fix: format!(
                "Fix: {label} received a null CUDA device destination for a non-zero memset. Allocate resident or transient device storage before enqueueing the clear."
            ),
        });
    }
    if stream.is_null() {
        return Err(BackendError::InvalidProgram {
            fix: format!(
                "Fix: {label} received a null CUDA stream for a non-zero memset. Use a backend-owned stream instead of the legacy default stream."
            ),
        });
    }
    Ok(())
}

/// Enqueue an async host-to-device copy on `stream`.
///
/// Zero-byte uploads are no-ops and do not touch CUDA. Non-zero uploads require
/// `src` and `dst` to be valid for `byte_len` bytes until `stream` reaches the
/// copy.
///
/// # Safety
///
/// The caller must guarantee that `src` points to a host allocation valid for
/// `byte_len`, `dst` is a valid device pointer for `byte_len`, and both remain
/// alive until the CUDA stream has completed the copy.
pub(crate) unsafe fn h2d_async_checked(
    dst: u64,
    src: *const c_void,
    byte_len: usize,
    stream: CUstream,
) -> Result<(), BackendError> {
    // SAFETY: Forwarding the caller's pointer and stream guarantees.
    unsafe { h2d_async_checked_with_label(dst, src, byte_len, stream, "cuMemcpyHtoDAsync_v2") }
}

/// Enqueue an async host-to-device copy with an operation label used in
/// diagnostics.
///
/// # Safety
///
/// Same as [`h2d_async_checked`].
pub(crate) unsafe fn h2d_async_checked_with_label(
    dst: u64,
    src: *const c_void,
    byte_len: usize,
    stream: CUstream,
    label: &'static str,
) -> Result<(), BackendError> {
    if byte_len == 0 {
        return Ok(());
    }
    validate_nonzero_host_to_device_copy(dst, src, stream, label)?;
    // SAFETY: The caller owns pointer validity and stream lifetime. This helper
    // centralizes result checking and the zero-byte no-op policy.
    unsafe {
        cuda_check(
            cudarc::driver::sys::cuMemcpyHtoDAsync_v2(dst, src, byte_len, stream),
            label,
        )
    }
}

/// Enqueue an async device-to-host copy on `stream`.
///
/// Zero-byte readbacks are no-ops and do not touch CUDA.
///
/// # Safety
///
/// The caller must guarantee that `dst` points to host storage valid for
/// `byte_len`, `src` is a valid device pointer for `byte_len`, and both remain
/// alive until the CUDA stream has completed the copy.
pub(crate) unsafe fn d2h_async_checked(
    dst: *mut c_void,
    src: u64,
    byte_len: usize,
    stream: CUstream,
) -> Result<(), BackendError> {
    // SAFETY: Forwarding the caller's pointer and stream guarantees.
    unsafe { d2h_async_checked_with_label(dst, src, byte_len, stream, "cuMemcpyDtoHAsync_v2") }
}

/// Enqueue an async device-to-host copy with an operation label used in
/// diagnostics.
///
/// # Safety
///
/// Same as [`d2h_async_checked`].
pub(crate) unsafe fn d2h_async_checked_with_label(
    dst: *mut c_void,
    src: u64,
    byte_len: usize,
    stream: CUstream,
    label: &'static str,
) -> Result<(), BackendError> {
    if byte_len == 0 {
        return Ok(());
    }
    validate_nonzero_device_to_host_copy(dst, src, stream, label)?;
    // SAFETY: The caller owns pointer validity and stream lifetime. This helper
    // centralizes result checking and the zero-byte no-op policy.
    unsafe {
        cuda_check(
            cudarc::driver::sys::cuMemcpyDtoHAsync_v2(dst, src, byte_len, stream),
            label,
        )
    }
}

/// Execute a synchronous device-to-host copy.
///
/// Zero-byte readbacks are no-ops and do not touch CUDA.
///
/// # Safety
///
/// The caller must guarantee that `dst` points to host storage valid for
/// `byte_len`, `src` is a valid device pointer for `byte_len`, and all prior
/// device writes visible to the copy have completed or are otherwise ordered.
pub(crate) unsafe fn d2h_sync_checked(
    dst: *mut c_void,
    src: u64,
    byte_len: usize,
) -> Result<(), BackendError> {
    // SAFETY: Forwarding the caller's pointer and ordering guarantees.
    unsafe { d2h_sync_checked_with_label(dst, src, byte_len, "cuMemcpyDtoH_v2") }
}

/// Execute a synchronous device-to-host copy with an operation label used in
/// diagnostics.
///
/// # Safety
///
/// Same as [`d2h_sync_checked`].
pub(crate) unsafe fn d2h_sync_checked_with_label(
    dst: *mut c_void,
    src: u64,
    byte_len: usize,
    label: &'static str,
) -> Result<(), BackendError> {
    if byte_len == 0 {
        return Ok(());
    }
    validate_nonzero_sync_device_to_host_copy(dst, src, label)?;
    // SAFETY: The caller owns pointer validity and ordering. This helper
    // centralizes result checking and the zero-byte no-op policy.
    unsafe {
        cuda_check(
            cudarc::driver::sys::cuMemcpyDtoH_v2(dst, src, byte_len),
            label,
        )
    }
}

/// Enqueue an async byte-pattern device memset on `stream`.
///
/// Zero-byte clears are no-ops and do not touch CUDA.
///
/// # Safety
///
/// The caller must guarantee that `dst` is a valid device pointer for
/// `byte_len` bytes and remains alive until the CUDA stream has completed the
/// memset.
pub(crate) unsafe fn memset_d8_async_checked(
    dst: u64,
    value: u8,
    byte_len: usize,
    stream: CUstream,
) -> Result<(), BackendError> {
    if byte_len == 0 {
        return Ok(());
    }
    validate_nonzero_device_memset(dst, stream, "cuMemsetD8Async")?;
    // SAFETY: The caller owns pointer validity and stream lifetime. This helper
    // centralizes result checking and zero-byte no-op behavior.
    unsafe {
        cuda_check(
            cudarc::driver::sys::cuMemsetD8Async(dst, value, byte_len, stream),
            "cuMemsetD8Async",
        )
    }
}

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

    #[test]
    fn zero_byte_h2d_copy_is_noop_before_cuda_ffi() {
        // SAFETY: The helper returns before dereferencing pointers or using the
        // stream when byte_len is zero.
        let result = unsafe { h2d_async_checked(0, std::ptr::null(), 0, std::ptr::null_mut()) };

        assert_eq!(
            result,
            Ok(()),
            "Fix: zero-byte H2D copies must not touch CUDA or require a live stream."
        );
    }

    #[test]
    fn zero_byte_d2h_copy_is_noop_before_cuda_ffi() {
        // SAFETY: The helper returns before dereferencing pointers or using the
        // stream when byte_len is zero.
        let result = unsafe { d2h_async_checked(std::ptr::null_mut(), 0, 0, std::ptr::null_mut()) };

        assert_eq!(
            result,
            Ok(()),
            "Fix: zero-byte D2H copies must not touch CUDA or require a live stream."
        );
    }

    #[test]
    fn zero_byte_sync_d2h_copy_is_noop_before_cuda_ffi() {
        // SAFETY: The helper returns before dereferencing pointers when byte_len
        // is zero.
        let result = unsafe { d2h_sync_checked(std::ptr::null_mut(), 0, 0) };

        assert_eq!(
            result,
            Ok(()),
            "Fix: zero-byte synchronous D2H copies must not touch CUDA."
        );
    }

    #[test]
    fn zero_byte_memset_is_noop_before_cuda_ffi() {
        // SAFETY: The helper returns before using the device pointer or stream
        // when byte_len is zero.
        let result = unsafe { memset_d8_async_checked(0, 0, 0, std::ptr::null_mut()) };

        assert_eq!(
            result,
            Ok(()),
            "Fix: zero-byte CUDA memsets must not touch CUDA or require a live stream."
        );
    }

    #[test]
    fn h2d_copy_helper_is_single_ffi_boundary() {
        let source = include_str!("copy.rs");
        assert!(source.contains("cuMemcpyHtoDAsync_v2"));
        assert!(source.contains("cuMemcpyDtoHAsync_v2"));
        assert!(source.contains("cuMemcpyDtoH_v2"));
        assert!(source.contains("cuMemsetD8Async"));
        assert!(
            source.contains("if byte_len == 0"),
            "Fix: shared copy primitives must preserve zero-byte no-op behavior."
        );
    }

    #[test]
    fn aligned_async_copy_len_rounds_to_cuda_dma_boundary() {
        assert_eq!(aligned_async_copy_len(0).unwrap(), 0);
        assert_eq!(aligned_async_copy_len(1).unwrap(), CUDA_ASYNC_COPY_ALIGNMENT);
        assert_eq!(aligned_async_copy_len(15).unwrap(), CUDA_ASYNC_COPY_ALIGNMENT);
        assert_eq!(aligned_async_copy_len(16).unwrap(), CUDA_ASYNC_COPY_ALIGNMENT);
        assert_eq!(aligned_async_copy_len(17).unwrap(), CUDA_ASYNC_COPY_ALIGNMENT * 2);
        assert!(
            aligned_async_copy_len(usize::MAX).is_err(),
            "Fix: CUDA async copy padding must report usize overflow instead of wrapping."
        );
    }

    #[test]
    fn nonzero_copy_helpers_reject_null_pointers_before_cuda_ffi() {
        let mut byte = 0u8;
        let host_ptr = (&mut byte as *mut u8).cast::<c_void>();
        let stream = std::ptr::NonNull::<cudarc::driver::sys::CUstream_st>::dangling().as_ptr();

        // SAFETY: The null device destination is intentional and must be
        // rejected by validation before CUDA FFI.
        let h2d_null_dst = unsafe { h2d_async_checked(0, host_ptr.cast_const(), 1, stream) }
            .expect_err("Fix: non-zero H2D copy with null device destination must fail pre-FFI.");
        assert!(h2d_null_dst
            .to_string()
            .contains("null CUDA device destination"));

        // SAFETY: The null host source is intentional and must be rejected by
        // validation before CUDA FFI.
        let h2d_null_src = unsafe { h2d_async_checked(1, std::ptr::null(), 1, stream) }
            .expect_err("Fix: non-zero H2D copy with null host source must fail pre-FFI.");
        assert!(h2d_null_src.to_string().contains("null host source"));

        let h2d_null_stream = {
            // SAFETY: The null stream is intentional and must be rejected by
            // validation before CUDA FFI.
            unsafe { h2d_async_checked(1, host_ptr.cast_const(), 1, std::ptr::null_mut()) }
        }
        .expect_err("Fix: non-zero H2D copy with null stream must fail pre-FFI.");
        assert!(h2d_null_stream.to_string().contains("null CUDA stream"));

        // SAFETY: The null host destination is intentional and must be rejected
        // by validation before CUDA FFI.
        let d2h_null_dst = unsafe { d2h_async_checked(std::ptr::null_mut(), 1, 1, stream) }
            .expect_err("Fix: non-zero D2H copy with null host destination must fail pre-FFI.");
        assert!(d2h_null_dst.to_string().contains("null host destination"));

        // SAFETY: The null device source is intentional and must be rejected by
        // validation before CUDA FFI.
        let d2h_null_src = unsafe { d2h_async_checked(host_ptr, 0, 1, stream) }
            .expect_err("Fix: non-zero D2H copy with null device source must fail pre-FFI.");
        assert!(d2h_null_src.to_string().contains("null CUDA device source"));

        // SAFETY: The null stream is intentional and must be rejected by
        // validation before CUDA FFI.
        let d2h_null_stream = unsafe { d2h_async_checked(host_ptr, 1, 1, std::ptr::null_mut()) }
            .expect_err("Fix: non-zero D2H copy with null stream must fail pre-FFI.");
        assert!(d2h_null_stream.to_string().contains("null CUDA stream"));

        // SAFETY: The null host destination is intentional and must be rejected
        // by validation before CUDA FFI.
        let sync_null_dst = unsafe { d2h_sync_checked(std::ptr::null_mut(), 1, 1) }.expect_err(
            "Fix: non-zero sync D2H copy with null host destination must fail pre-FFI.",
        );
        assert!(sync_null_dst.to_string().contains("null host destination"));

        // SAFETY: The null device source is intentional and must be rejected by
        // validation before CUDA FFI.
        let sync_null_src = unsafe { d2h_sync_checked(host_ptr, 0, 1) }
            .expect_err("Fix: non-zero sync D2H copy with null device source must fail pre-FFI.");
        assert!(sync_null_src
            .to_string()
            .contains("null CUDA device source"));

        // SAFETY: The null device destination is intentional and must be
        // rejected by validation before CUDA FFI.
        let memset_null_dst = unsafe { memset_d8_async_checked(0, 0, 1, stream) }
            .expect_err("Fix: non-zero memset with null device destination must fail pre-FFI.");
        assert!(memset_null_dst
            .to_string()
            .contains("null CUDA device destination"));

        // SAFETY: The null stream is intentional and must be rejected by
        // validation before CUDA FFI.
        let memset_null_stream = unsafe { memset_d8_async_checked(1, 0, 1, std::ptr::null_mut()) }
            .expect_err("Fix: non-zero memset with null stream must fail pre-FFI.");
        assert!(memset_null_stream.to_string().contains("null CUDA stream"));
    }

    #[test]
    fn copy_boundary_validates_nonzero_inputs_before_ffi() {
        let source = include_str!("copy.rs");
        assert!(
            source.contains("validate_nonzero_host_to_device_copy")
                && source.contains("validate_nonzero_device_to_host_copy")
                && source.contains("validate_nonzero_sync_device_to_host_copy")
                && source.contains("validate_nonzero_device_memset"),
            "Fix: shared CUDA copy primitives must validate non-zero pointer and stream inputs before FFI."
        );
    }

    #[test]
    fn resident_staged_sync_readback_uses_shared_copy_helper() {
        let resident_dispatch = include_str!("resident_dispatch.rs");
        let ffi = concat!("cudarc::driver::sys::", "cuMemcpyDtoH_v2(");

        assert_eq!(
            resident_dispatch.matches(ffi).count(),
            0,
            "Fix: resident staged synchronous readback must route through copy::d2h_sync_checked_with_label."
        );
        assert!(
            resident_dispatch.contains("copy::d2h_sync_checked_with_label"),
            "Fix: resident staged synchronous readback must use the shared copy boundary."
        );
    }
}