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
use std::sync::Arc;

use super::DeviceMemory;
use crate::{
    error::{Error, Result},
    memory::{MemoryCopyKind, PinnedHostSlice, PinnedHostSliceMut, transfer},
    stream::{Stream, StreamScope},
    submission::{Access, AccessMode},
    utility::checked_bytes,
    view::{AnyBitPatternDeviceRepr, DeviceRegionProvider, DeviceRepr, DeviceSlice, HostSlice},
};

impl<T> DeviceMemory<T> {
    /// Copies host values and waits until the device range contains the uploaded values.
    ///
    /// # Errors
    ///
    /// Returns an error for unequal element counts or byte-size overflow.
    /// Also propagates access-tracking, readiness synchronization, context-binding, stream-capture, CUDA copy, and stream synchronization errors.
    /// A nonempty synchronous transfer is rejected during stream capture.
    pub fn copy_from_host(&mut self, host_slice: &[T]) -> Result<()>
    where
        T: DeviceRepr,
    {
        transfer::copy_from_host(self, host_slice)
    }

    /// Copies from page-locked host memory into this device allocation.
    ///
    /// The source length must match this allocation's length.
    /// This is the pinned-memory-specific counterpart to [`DeviceMemory::copy_from_host`].
    ///
    /// # Errors
    ///
    /// Returns an error if the lengths differ, byte-size arithmetic overflows, or CUDA rejects the host-to-device copy.
    pub fn copy_from_pinned<B>(&mut self, src: &B) -> Result<()>
    where
        B: PinnedHostSlice<T> + ?Sized,
        T: DeviceRepr,
    {
        let context = Arc::clone(self.context());
        self.bind()?;
        let () = T::LAYOUT;
        if HostSlice::len(src) != self.length {
            return Err(Error::length_mismatch(
                "host source",
                self.length,
                HostSlice::len(src),
            ));
        }

        if self.length == 0 {
            return Ok(());
        }

        checked_bytes::<T>(self.length, "byte length")?;
        let _access = context.acquire_accesses(&[
            Access::new(self.region(), AccessMode::Write),
            Access::host(src.host_region(), AccessMode::Read),
        ])?;
        // SAFETY: the guards acquired above cover both regions, and the lengths were checked to match.
        unsafe {
            transfer::copy_synchronous(
                self.ptr,
                src.as_host_ptr(),
                self.length,
                MemoryCopyKind::HostToDevice,
                None,
            )
        }
    }

    /// Enqueues a copy from page-locked host memory into this device allocation.
    ///
    /// The [`StreamScope`] ties the source and destination lifetimes to the queued copy.
    ///
    /// # Errors
    ///
    /// Returns an error if the lengths differ, byte-size arithmetic overflows, or CUDA cannot enqueue the host-to-device copy.
    pub fn copy_from_pinned_scoped<'env, B>(
        &'env mut self,
        src: &'env B,
        stream: &StreamScope<'_, 'env>,
    ) -> Result<()>
    where
        B: PinnedHostSlice<T> + ?Sized,
        T: DeviceRepr,
    {
        self.bind_stream(stream.stream())?;
        let () = T::LAYOUT;
        if HostSlice::len(src) != self.length {
            return Err(Error::length_mismatch(
                "host source",
                self.length,
                HostSlice::len(src),
            ));
        }

        checked_bytes::<T>(self.length, "byte length")?;
        if self.length == 0 {
            return Ok(());
        }

        let accesses = [
            Access::new(self.region(), AccessMode::Write),
            Access::host(src.host_region(), AccessMode::Read),
        ];
        // SAFETY: the declared accesses retain both regions, and the stream orders every access to them.
        unsafe {
            stream.enqueue(&accesses, || {
                Self::copy_async(
                    self.ptr,
                    src.as_host_ptr(),
                    self.length,
                    MemoryCopyKind::HostToDevice,
                    stream.stream(),
                )
            })
        }
    }

    /// Enqueues a host-to-device copy of the entire allocation in a stream scope.
    ///
    /// The scope retains both borrows until the transfer completes.
    ///
    /// # Errors
    ///
    /// Returns an error if the element counts differ, the byte count overflows, or the scope’s stream belongs to another context.
    /// Also propagates context-binding, scope submission, and CUDA copy errors.
    pub fn copy_from_host_scoped<'env>(
        &'env mut self,
        host_slice: &'env [T],
        stream: &StreamScope<'_, 'env>,
    ) -> Result<()>
    where
        T: DeviceRepr,
    {
        let () = T::LAYOUT;
        if host_slice.len() != self.len() {
            return Err(Error::length_mismatch(
                "host slice",
                self.len(),
                host_slice.len(),
            ));
        }

        checked_bytes::<T>(self.len(), "byte length")?;
        self.bind_stream(stream.stream())?;
        if self.is_empty() {
            return Ok(());
        }

        let accesses = [Access::new(self.region(), AccessMode::Write)];
        // SAFETY: the declared accesses retain both regions, and the stream orders every access to them.
        unsafe {
            stream.enqueue(&accesses, || {
                Self::copy_async(
                    self.ptr,
                    host_slice.as_ptr(),
                    self.len(),
                    MemoryCopyKind::HostToDevice,
                    stream.stream(),
                )
            })
        }
    }

    /// Enqueues a copy of `host_slice` into this allocation on `stream`.
    ///
    /// # Safety
    ///
    /// The caller must ensure `self` and `host_slice` both remain valid until `stream` has completed the transfer.
    ///
    /// # Errors
    ///
    /// Returns an error if the host and device element counts differ, the stream belongs to another context, or the byte count overflows.
    /// Also propagates context-binding, producer-ordering, and CUDA asynchronous copy errors.
    pub unsafe fn copy_from_host_async(&mut self, host_slice: &[T], stream: &Stream) -> Result<()> {
        self.bind_stream(stream)?;
        if host_slice.len() != self.len() {
            return Err(Error::length_mismatch(
                "host slice",
                self.len(),
                host_slice.len(),
            ));
        }

        if self.is_empty() {
            return Ok(());
        }

        stream.join_regions(&[self.region()])?;
        // SAFETY: the lengths match, `stream` is ordered after the allocation's producer, and the caller keeps both ranges valid until `stream` completes the copy.
        unsafe {
            Self::copy_async(
                self.as_mut_ptr(),
                host_slice.as_ptr(),
                self.len(),
                MemoryCopyKind::HostToDevice,
                stream,
            )
        }
    }

    /// Copies all device elements into an equally sized host slice and waits for completion.
    ///
    /// # Errors
    ///
    /// Returns an error for unequal element counts or byte-size overflow.
    /// Also propagates access-tracking, readiness synchronization, context-binding, stream-capture, CUDA copy, and stream synchronization errors.
    /// A nonempty synchronous transfer is rejected during stream capture.
    pub fn copy_to_host(&self, host_slice: &mut [T]) -> Result<()>
    where
        T: AnyBitPatternDeviceRepr,
    {
        transfer::copy_to_host(self, host_slice)
    }

    /// Copies device values to host storage under a kernel-specific validity contract.
    ///
    /// # Safety
    ///
    /// Every source element must be initialized and contain a valid value of `T`.
    /// `T` must be transferable without duplicating ownership or host references.
    ///
    /// # Errors
    ///
    /// Returns an error if host and device element counts differ or the byte count overflows.
    /// Also propagates access-tracking, readiness synchronization, context-binding, stream-capture, CUDA copy, and stream synchronization errors.
    /// A nonempty synchronous transfer is rejected during stream capture.
    pub unsafe fn copy_to_host_unchecked(&self, host_slice: &mut [T]) -> Result<()>
    where
        T: DeviceRepr,
    {
        // SAFETY: the caller vouches that every source element is a valid, transferable `T`.
        unsafe { transfer::copy_to_host_unchecked(self, host_slice) }
    }

    /// Copies this device allocation into page-locked host memory.
    ///
    /// The destination length must match this allocation's length.
    /// This is the pinned-memory-specific counterpart to [`DeviceMemory::copy_to_host`].
    ///
    /// # Errors
    ///
    /// Returns an error if the lengths differ, byte-size arithmetic overflows, or CUDA rejects the device-to-host copy.
    pub fn copy_to_pinned<B>(&self, dst: &mut B) -> Result<()>
    where
        B: PinnedHostSliceMut<T> + ?Sized,
        T: AnyBitPatternDeviceRepr,
    {
        let context = Arc::clone(self.context());
        self.bind()?;
        let () = T::LAYOUT;
        if HostSlice::len(dst) != self.length {
            return Err(Error::length_mismatch(
                "host destination",
                self.length,
                HostSlice::len(dst),
            ));
        }

        if self.length == 0 {
            return Ok(());
        }

        checked_bytes::<T>(self.length, "byte length")?;
        let _access = context.acquire_accesses(&[
            Access::new(self.region(), AccessMode::Read),
            Access::host(dst.host_region(), AccessMode::Write),
        ])?;
        // SAFETY: the guards acquired above cover both regions, and the lengths were checked to match.
        unsafe {
            transfer::copy_synchronous(
                dst.as_host_mut_ptr(),
                self.ptr,
                self.length,
                MemoryCopyKind::DeviceToHost,
                None,
            )
        }
    }

    /// Enqueues a copy from this device allocation into page-locked host memory.
    ///
    /// The [`StreamScope`] ties the source and destination lifetimes to the queued copy.
    ///
    /// # Errors
    ///
    /// Returns an error if the lengths differ, byte-size arithmetic overflows, or CUDA cannot enqueue the device-to-host copy.
    pub fn copy_to_pinned_scoped<'env, B>(
        &'env self,
        dst: &'env mut B,
        stream: &StreamScope<'_, 'env>,
    ) -> Result<()>
    where
        B: PinnedHostSliceMut<T> + ?Sized,
        T: AnyBitPatternDeviceRepr,
    {
        self.bind_stream(stream.stream())?;
        let () = T::LAYOUT;
        if HostSlice::len(dst) != self.length {
            return Err(Error::length_mismatch(
                "host destination",
                self.length,
                HostSlice::len(dst),
            ));
        }

        checked_bytes::<T>(self.length, "byte length")?;
        if self.length == 0 {
            return Ok(());
        }

        let accesses = [
            Access::new(self.region(), AccessMode::Read),
            Access::host(dst.host_region(), AccessMode::Write),
        ];
        // SAFETY: the declared accesses retain both regions, and the stream orders every access to them.
        unsafe {
            stream.enqueue(&accesses, || {
                Self::copy_async(
                    dst.as_host_mut_ptr(),
                    self.ptr,
                    self.length,
                    MemoryCopyKind::DeviceToHost,
                    stream.stream(),
                )
            })
        }
    }

    /// Enqueues a device-to-host copy of the entire allocation in a stream scope.
    ///
    /// The scope retains the source and exclusive destination borrows until the transfer completes.
    ///
    /// # Errors
    ///
    /// Returns an error if the element counts differ, the byte count overflows, or the scope’s stream belongs to another context.
    /// Also propagates context-binding, scope submission, and CUDA copy errors.
    pub fn copy_to_host_scoped<'env>(
        &'env self,
        host_slice: &'env mut [T],
        stream: &StreamScope<'_, 'env>,
    ) -> Result<()>
    where
        T: AnyBitPatternDeviceRepr,
    {
        let () = T::LAYOUT;
        if host_slice.len() != self.len() {
            return Err(Error::length_mismatch(
                "host slice",
                self.len(),
                host_slice.len(),
            ));
        }

        checked_bytes::<T>(self.len(), "byte length")?;
        self.bind_stream(stream.stream())?;
        if self.is_empty() {
            return Ok(());
        }

        let accesses = [Access::new(self.region(), AccessMode::Read)];
        // SAFETY: the declared accesses retain both regions, and the stream orders every access to them.
        unsafe {
            stream.enqueue(&accesses, || {
                Self::copy_async(
                    host_slice.as_mut_ptr(),
                    self.ptr,
                    self.len(),
                    MemoryCopyKind::DeviceToHost,
                    stream.stream(),
                )
            })
        }
    }

    /// Enqueues a copy of this allocation into `host_slice` on `stream`.
    ///
    /// # Safety
    ///
    /// The caller must ensure `self` and `host_slice` both remain valid until `stream` has completed the transfer.
    /// Every source element must be initialized and valid for `T`, without Rust ownership or host references.
    ///
    /// # Errors
    ///
    /// Returns an error if the host and device element counts differ, the stream belongs to another context, or the byte count overflows.
    /// Also propagates context-binding, producer-ordering, and CUDA asynchronous copy errors.
    pub unsafe fn copy_to_host_async(&self, host_slice: &mut [T], stream: &Stream) -> Result<()> {
        self.bind_stream(stream)?;
        if host_slice.len() != self.len() {
            return Err(Error::length_mismatch(
                "host slice",
                self.len(),
                host_slice.len(),
            ));
        }

        if self.is_empty() {
            return Ok(());
        }

        stream.join_regions(&[self.region()])?;
        // SAFETY: the lengths match, `stream` is ordered after the allocation's producer, and the caller keeps both ranges valid until `stream` completes and vouches for the source values.
        unsafe {
            Self::copy_async(
                host_slice.as_mut_ptr(),
                self.as_ptr(),
                self.len(),
                MemoryCopyKind::DeviceToHost,
                stream,
            )
        }
    }

    /// Copies all device elements into a new host vector and waits for completion.
    ///
    /// # Errors
    ///
    /// Propagates byte-size overflow, access-tracking, readiness synchronization, context-binding, stream-capture, CUDA copy, and stream synchronization errors.
    /// A nonempty synchronous transfer is rejected during stream capture.
    pub fn copy_to_host_vec(&self) -> Result<Vec<T>>
    where
        T: AnyBitPatternDeviceRepr,
    {
        transfer::copy_to_host_vec(self)
    }

    /// Copies initialized device values into a host vector under a kernel-specific validity contract.
    ///
    /// # Safety
    ///
    /// Every source element must contain a valid value of `T`.
    /// `T` must be transferable without duplicating ownership or host references.
    ///
    /// # Errors
    ///
    /// Propagates byte-size, access-tracking, readiness synchronization, context-binding, stream-capture, CUDA copy, and stream synchronization errors.
    /// A nonempty synchronous transfer is rejected during stream capture.
    pub unsafe fn copy_to_host_vec_unchecked(&self) -> Result<Vec<T>> {
        let context = Arc::clone(self.context());
        let _access = context.acquire_host_access(&[self.region()])?;
        self.bind()?;
        // SAFETY: the context is bound, the access guard orders tracked producers, `ptr` holds `length` elements, and the caller vouches that each is a valid `T`.
        unsafe {
            transfer::copy_to_host_vec_unchecked(self.ptr, self.length, self.region().stream())
        }
    }

    /// Copies a disjoint device range into this allocation and waits for completion.
    ///
    /// # Errors
    ///
    /// Returns an error if contexts or element counts differ, the ranges overlap within one allocation, or the byte count overflows.
    /// Also propagates access-tracking, readiness synchronization, context-binding, stream-capture, CUDA copy, and stream synchronization errors.
    /// A nonempty synchronous transfer is rejected during stream capture.
    pub fn copy_from_device<S>(&mut self, source: &S) -> Result<()>
    where
        T: DeviceRepr,
        S: DeviceSlice<T> + ?Sized,
    {
        transfer::copy_device(self, source)
    }

    /// Enqueues a device-to-device copy of the entire allocation in a stream scope.
    ///
    /// The scope retains both borrows until the transfer completes.
    ///
    /// # Errors
    ///
    /// Returns an error if source and destination contexts or element counts differ, the byte count overflows, or the scope’s stream belongs to another context.
    /// Also propagates context-binding, scope submission, and CUDA copy errors.
    pub fn copy_from_device_scoped<'env>(
        &'env mut self,
        src: &'env Self,
        stream: &StreamScope<'_, 'env>,
    ) -> Result<()> {
        if self.context() != src.context() {
            return Err(Error::MemoryContextMismatch);
        }

        if src.len() != self.len() {
            return Err(Error::length_mismatch("source", self.len(), src.len()));
        }

        checked_bytes::<T>(self.len(), "byte length")?;
        self.bind_stream(stream.stream())?;
        if self.is_empty() {
            return Ok(());
        }

        let accesses = [
            Access::new(self.region(), AccessMode::Write),
            Access::new(src.region(), AccessMode::Read),
        ];
        // SAFETY: the declared accesses retain both regions, and the stream orders every access to them.
        unsafe {
            stream.enqueue(&accesses, || {
                Self::copy_async(
                    self.ptr,
                    src.as_ptr(),
                    self.len(),
                    MemoryCopyKind::DeviceToDevice,
                    stream.stream(),
                )
            })
        }
    }

    /// Enqueues a copy of `src` into this allocation on `stream`.
    ///
    /// # Safety
    ///
    /// The caller must ensure `self` and `src` both remain valid until `stream` has completed the transfer.
    ///
    /// # Errors
    ///
    /// Returns an error if source and destination contexts or element counts differ, the stream belongs to another context, or the byte count overflows.
    /// Also propagates context-binding, producer-ordering, and CUDA asynchronous copy errors.
    pub unsafe fn copy_from_device_async(&mut self, src: &Self, stream: &Stream) -> Result<()> {
        if self.context() != src.context() {
            return Err(Error::MemoryContextMismatch);
        }

        self.bind_stream(stream)?;
        if src.len() != self.len() {
            return Err(Error::length_mismatch("source", self.len(), src.len()));
        }

        if self.is_empty() {
            return Ok(());
        }

        stream.join_regions(&[self.region(), src.region()])?;
        // SAFETY: contexts and lengths match, `&mut self` keeps the ranges disjoint, `stream` is ordered after both producers, and the caller keeps both valid until `stream` completes.
        unsafe {
            Self::copy_async(
                self.as_mut_ptr(),
                src.as_ptr(),
                self.len(),
                MemoryCopyKind::DeviceToDevice,
                stream,
            )
        }
    }
}