forked from chelsea0x3b/cudarc
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcore.rs
More file actions
2176 lines (1970 loc) · 73.4 KB
/
Copy pathcore.rs
File metadata and controls
2176 lines (1970 loc) · 73.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use crate::driver::{
result::{self, DriverError},
sys::{self, CUfunc_cache_enum, CUfunction_attribute_enum},
};
use std::{
ffi::CString,
marker::PhantomData,
ops::{Bound, RangeBounds},
string::String,
sync::atomic::{AtomicBool, AtomicU32, AtomicUsize, Ordering},
sync::Arc,
vec::Vec,
};
/// Represents a primary cuda context on a certain device. When created with [CudaContext::new()] it will
/// push a new primary context onto the stack.
///
/// This is the entrypoint to using any cuda calls, all objects maintain a pointer to `Arc<CudaContext>`
/// to ensure proper lifetimes.
///
/// # On thread safety
///
/// This object is thread safe and can be shared/used on multiple threads. All safe apis call
/// [CudaContext::bind_to_thread()] before doing work in a certain context.
#[derive(Debug)]
pub struct CudaContext {
pub(crate) cu_device: sys::CUdevice,
pub(crate) cu_ctx: sys::CUcontext,
pub(crate) ordinal: usize,
pub(crate) has_async_alloc: bool,
pub(crate) num_streams: AtomicUsize,
pub(crate) event_tracking: AtomicBool,
pub(crate) error_state: AtomicU32,
}
unsafe impl Send for CudaContext {}
unsafe impl Sync for CudaContext {}
impl Drop for CudaContext {
fn drop(&mut self) {
self.record_err(self.bind_to_thread());
let ctx = std::mem::replace(&mut self.cu_ctx, std::ptr::null_mut());
if !ctx.is_null() {
self.record_err(unsafe { result::primary_ctx::release(self.cu_device) });
}
}
}
impl PartialEq for CudaContext {
fn eq(&self, other: &Self) -> bool {
self.cu_device == other.cu_device
&& self.cu_ctx == other.cu_ctx
&& self.ordinal == other.ordinal
}
}
impl Eq for CudaContext {}
impl CudaContext {
/// Creates a new context on the specified device ordinal.
pub fn new(ordinal: usize) -> Result<Arc<Self>, DriverError> {
result::init()?;
let cu_device = result::device::get(ordinal as i32)?;
let cu_ctx = unsafe { result::primary_ctx::retain(cu_device) }?;
let has_async_alloc = unsafe {
let memory_pools_supported = result::device::get_attribute(
cu_device,
sys::CUdevice_attribute_enum::CU_DEVICE_ATTRIBUTE_MEMORY_POOLS_SUPPORTED,
)?;
memory_pools_supported > 0
};
let ctx = Arc::new(CudaContext {
cu_device,
cu_ctx,
ordinal,
has_async_alloc,
num_streams: AtomicUsize::new(0),
event_tracking: AtomicBool::new(true),
error_state: AtomicU32::new(0),
});
ctx.bind_to_thread()?;
Ok(ctx)
}
/// The number of devices available.
pub fn device_count() -> Result<i32, DriverError> {
result::init()?;
result::device::get_count()
}
/// Get the `ordinal` index of the device this is on.
pub fn ordinal(&self) -> usize {
self.ordinal
}
/// Get the name of this device.
pub fn name(&self) -> Result<String, result::DriverError> {
self.check_err()?;
result::device::get_name(self.cu_device)
}
/// Get the UUID of this device.
pub fn uuid(&self) -> Result<sys::CUuuid, result::DriverError> {
self.check_err()?;
result::device::get_uuid(self.cu_device)
}
/// Get the underlying [sys::CUdevice] of this [CudaContext].
///
/// # Safety
/// While this function is marked as safe, actually using the
/// returned object is unsafe.
///
/// **You must not free/release the device pointer**, as it is still
/// owned by the [CudaContext].
pub fn cu_device(&self) -> sys::CUdevice {
self.cu_device
}
/// Get the underlying [sys::CUcontext] of this [CudaContext].
///
/// # Safety
/// While this function is marked as safe, actually using the
/// returned object is unsafe.
///
/// **You must not free/release the context pointer**, as it is still
/// owned by the [CudaContext].
pub fn cu_ctx(&self) -> sys::CUcontext {
self.cu_ctx
}
/// Binds this context to the calling thread. Calling this is key for thread safety.
pub fn bind_to_thread(&self) -> Result<(), DriverError> {
self.check_err()?;
if match result::ctx::get_current()? {
Some(curr_ctx) => curr_ctx != self.cu_ctx,
None => true,
} {
unsafe { result::ctx::set_current(self.cu_ctx) }?;
}
Ok(())
}
/// Get the value of the specified attribute of the device in [CudaContext].
pub fn attribute(&self, attrib: sys::CUdevice_attribute) -> Result<i32, result::DriverError> {
self.check_err()?;
unsafe { result::device::get_attribute(self.cu_device, attrib) }
}
/// Synchronize this context. Will only block CPU if you call [CudaContext::set_flags()] with
/// [sys::CUctx_flags::CU_CTX_SCHED_BLOCKING_SYNC].
pub fn synchronize(&self) -> Result<(), DriverError> {
self.bind_to_thread()?;
result::ctx::synchronize()
}
/// Ensures calls to [CudaContext::synchronize()] block the calling thread.
///
/// Sets [sys::CUctx_flags::CU_CTX_SCHED_BLOCKING_SYNC]
#[cfg(not(any(
feature = "cuda-11040",
feature = "cuda-11050",
feature = "cuda-11060",
feature = "cuda-11070",
feature = "cuda-11080",
feature = "cuda-12000"
)))]
pub fn set_blocking_synchronize(&self) -> Result<(), DriverError> {
self.set_flags(sys::CUctx_flags::CU_CTX_SCHED_BLOCKING_SYNC)
}
/// Set flags for this context
#[cfg(not(any(
feature = "cuda-11040",
feature = "cuda-11050",
feature = "cuda-11060",
feature = "cuda-11070",
feature = "cuda-11080",
feature = "cuda-12000"
)))]
pub fn set_flags(&self, flags: sys::CUctx_flags) -> Result<(), DriverError> {
self.bind_to_thread()?;
result::ctx::set_flags(flags)
}
/// Whether multiple streams have been created in this context. If so,
/// the [CudaSlice::read] and [CudaSlice::write] events will be activated.
///
/// This only get's set to true by [CudaContext::new_stream()].
pub fn is_in_multi_stream_mode(&self) -> bool {
self.num_streams.load(Ordering::Relaxed) > 0
}
/// Whether event tracking is being managed by this context
/// (via [CudaContext::enable_event_tracking()], which is the default behavior),
/// or `false` if the user is manually managing stream synchronization
/// (via [CudaContext::disable_event_tracking()]).
pub fn is_event_tracking(&self) -> bool {
self.event_tracking.load(Ordering::Relaxed)
}
/// Whether the context is automatically managing multiple stream synchronization.
/// Both of these must be true:
/// - [CudaContext::is_in_multi_stream_mode()]
/// - [CudaContext::is_event_tracking()]
pub fn is_managing_stream_synchronization(&self) -> bool {
self.is_in_multi_stream_mode() && self.is_event_tracking()
}
/// When turned on, all [CudaSlice] **created after calling this function** will
/// record usages using [CudaEvent] to ensure proper synchronization between streams.
///
/// # Safety
///
/// If [CudaContext::disable_event_tracking()] was called previously, then any
/// [CudaSlice] created after that and before this current call won't have [CudaEvent]
/// tracking their uses. Those [CudaSlice] will not manage their synchronization, even
/// after this call.
pub unsafe fn enable_event_tracking(&self) {
self.event_tracking.store(true, Ordering::Relaxed);
}
/// When turned on, all [CudaSlice] **created after calling this function** will
/// not track uses via [CudaEvent]s.
///
/// # Safety
///
/// It is up to the user to ensure proper synchronization between multiple streams:
/// - Ensure that no [CudaSlice] is freed before a use on another stream is finished.
/// - Ensure that a [CudaSlice] is not used on another stream before allocation on the
/// allocating stream finishes.
/// - Ensure that a [CudaSlice] is not written two concurrently by multiple streams.
pub unsafe fn disable_event_tracking(&self) {
self.event_tracking.store(false, Ordering::Relaxed);
}
/// Checks to see if there have been any calls that stored an Err in a function
/// that couldn't return a result (e.g. Drop calls).
///
/// If there are any errors stored, this method will return the Err value, and
/// then clear the stored error state.
pub fn check_err(&self) -> Result<(), DriverError> {
let error_state = self.error_state.swap(0, Ordering::Relaxed);
if error_state == 0 {
Ok(())
} else {
Err(result::DriverError(unsafe {
std::mem::transmute::<u32, sys::cudaError_enum>(error_state)
}))
}
}
/// Records a result for later inspection when a Result can be returned.
pub fn record_err<T>(&self, result: Result<T, DriverError>) {
if let Err(err) = result {
self.error_state.store(err.0 as u32, Ordering::Relaxed)
}
}
}
/// A lightweight synchronization primitive used to synchronize between [CudaStream]s.
///
/// - Create using [CudaContext::new_event()].
/// - Record a point of time in a stream using [CudaEvent::record()].
/// - Either call [CudaEvent::synchronize()] or [CudaStream::wait()] to use.
///
/// Note that calls to [CudaEvent::record()] will not change any **previous calls** to [CudaStream::wait()].
///
/// # Thread safety
/// This object is thread safe
#[derive(Debug)]
pub struct CudaEvent {
pub(crate) cu_event: sys::CUevent,
pub(crate) ctx: Arc<CudaContext>,
}
unsafe impl Send for CudaEvent {}
unsafe impl Sync for CudaEvent {}
impl Drop for CudaEvent {
fn drop(&mut self) {
self.ctx.record_err(self.ctx.bind_to_thread());
self.ctx
.record_err(unsafe { result::event::destroy(self.cu_event) });
}
}
impl CudaContext {
/// Creates a new [CudaEvent] with no work recorded. If `flags` is None, the event is created with
/// [sys::CUevent_flags::CU_EVENT_DISABLE_TIMING].
pub fn new_event(
self: &Arc<Self>,
flags: Option<sys::CUevent_flags>,
) -> Result<CudaEvent, DriverError> {
let flags = flags.unwrap_or(sys::CUevent_flags::CU_EVENT_DISABLE_TIMING);
self.bind_to_thread()?;
let cu_event = result::event::create(flags)?;
Ok(CudaEvent {
cu_event,
ctx: self.clone(),
})
}
}
impl CudaEvent {
/// The underlying cu_event object.
///
/// # Safety
/// Do not destroy this value
pub fn cu_event(&self) -> sys::CUevent {
self.cu_event
}
/// The context this was created in.
pub fn context(&self) -> &Arc<CudaContext> {
&self.ctx
}
/// Records the current amount of work in [CudaStream] into this event.
///
/// **This does not affect any previous calls to [CudaStream::wait()]**
///
/// If `stream` belongs to a different [CudaContext], this will fail with
/// [sys::cudaError_enum::CUDA_ERROR_INVALID_CONTEXT].
///
/// See [cuda docs](https://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__EVENT.html#group__CUDA__EVENT_1g95424d3be52c4eb95d83861b70fb89d1)
pub fn record(&self, stream: &CudaStream) -> Result<(), DriverError> {
if self.ctx != stream.ctx {
return Err(DriverError(sys::cudaError_enum::CUDA_ERROR_INVALID_CONTEXT));
}
self.ctx.bind_to_thread()?;
unsafe { result::event::record(self.cu_event, stream.cu_stream) }
}
/// Will only block CPU thraed if [sys::CUevent_flags::CU_EVENT_BLOCKING_SYNC] was used to create this event.
pub fn synchronize(&self) -> Result<(), DriverError> {
self.ctx.bind_to_thread()?;
unsafe { result::event::synchronize(self.cu_event) }
}
/// The time between two events. `self` is the start event, and `end` is the end event.
/// This is effectively `end - self`.
pub fn elapsed_ms(&self, end: &Self) -> Result<f32, DriverError> {
if self.ctx != end.ctx {
return Err(DriverError(sys::cudaError_enum::CUDA_ERROR_INVALID_CONTEXT));
}
self.ctx.bind_to_thread()?;
self.synchronize()?;
end.synchronize()?;
unsafe { result::event::elapsed(self.cu_event, end.cu_event) }
}
/// Returns `true` if all recorded work has been completed, `false` otherwise.
pub fn is_complete(&self) -> bool {
unsafe { result::event::query(self.cu_event) }.is_ok()
}
}
/// A wrapper around [sys::CUstream] that you can schedule work on.
///
/// - Create with [CudaContext::new_stream()], [CudaContext::default_stream()], or [CudaStream::fork()].
///
/// **Work done on this is asynchronous with respect to the host.**
///
/// See [CUDA C/C++ Streams and Concurrency](https://developer.download.nvidia.com/CUDA/training/StreamsAndConcurrencyWebinar.pdf)
/// See [3. Stream synchronization behavior](https://docs.nvidia.com/cuda/cuda-runtime-api/stream-sync-behavior.html)
/// See [6.6. Event Management](https://docs.nvidia.com/cuda/cuda-runtime-api/group__CUDART__EVENT.html)
/// See [Out-of-order execution](https://en.wikipedia.org/wiki/Out-of-order_execution)
/// See [Dependence analysis](https://en.wikipedia.org/wiki/Dependence_analysis)
#[derive(Debug, PartialEq, Eq)]
pub struct CudaStream {
pub(crate) cu_stream: sys::CUstream,
pub(crate) ctx: Arc<CudaContext>,
}
unsafe impl Send for CudaStream {}
unsafe impl Sync for CudaStream {}
impl Drop for CudaStream {
fn drop(&mut self) {
self.ctx.record_err(self.ctx.bind_to_thread());
if !self.cu_stream.is_null() {
self.ctx.num_streams.fetch_sub(1, Ordering::Relaxed);
self.ctx
.record_err(unsafe { result::stream::destroy(self.cu_stream) });
}
}
}
impl CudaContext {
/// Get's the default stream for this context (the null ptr stream). Note that context's
/// on the same device can all submit to the same default stream from separate context objects.
pub fn default_stream(self: &Arc<Self>) -> Arc<CudaStream> {
Arc::new(CudaStream {
cu_stream: std::ptr::null_mut(),
ctx: self.clone(),
})
}
/// Create a new [sys::CUstream_flags::CU_STREAM_NON_BLOCKING] stream.
///
/// This will swap the calling context to multi stream mode [CudaContext::is_in_multi_stream_mode()].
/// If the context is not already in multiple stream mode, then this function will also call [CudaContext::synchronize()].
pub fn new_stream(self: &Arc<Self>) -> Result<Arc<CudaStream>, DriverError> {
self.bind_to_thread()?;
let prev_num_streams = self.num_streams.fetch_add(1, Ordering::Relaxed);
if prev_num_streams == 0 && self.is_event_tracking() {
self.synchronize()?;
}
let cu_stream = result::stream::create(result::stream::StreamKind::NonBlocking)?;
Ok(Arc::new(CudaStream {
cu_stream,
ctx: self.clone(),
}))
}
}
impl CudaStream {
/// Create's a new stream and then makes the new stream wait on `self`
pub fn fork(&self) -> Result<Arc<Self>, DriverError> {
self.ctx.bind_to_thread()?;
self.ctx.num_streams.fetch_add(1, Ordering::Relaxed);
let cu_stream = result::stream::create(result::stream::StreamKind::NonBlocking)?;
let stream = Arc::new(CudaStream {
cu_stream,
ctx: self.ctx.clone(),
});
stream.join(self)?;
Ok(stream)
}
/// The underlying cuda stream object
/// # Safety
/// Do not destroy this value.
pub fn cu_stream(&self) -> sys::CUstream {
self.cu_stream
}
/// The context the stream belongs to.
pub fn context(&self) -> &Arc<CudaContext> {
&self.ctx
}
/// Will only block CPU if you call [CudaContext::set_flags()] with
/// [sys::CUctx_flags::CU_CTX_SCHED_BLOCKING_SYNC].
///
/// See [cuda docs](https://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__STREAM.html#group__CUDA__STREAM_1g15e49dd91ec15991eb7c0a741beb7dad)
pub fn synchronize(&self) -> Result<(), DriverError> {
self.ctx.bind_to_thread()?;
unsafe { result::stream::synchronize(self.cu_stream) }
}
/// Creates a new [CudaEvent] and records the current work in the stream to the event.
pub fn record_event(
&self,
flags: Option<sys::CUevent_flags>,
) -> Result<CudaEvent, DriverError> {
let event = self.ctx.new_event(flags)?;
event.record(self)?;
Ok(event)
}
/// Waits for the work recorded in [CudaEvent] to be completed.
///
/// You can record new work in `event` after calling this method without
/// affecting this call.
///
/// See [cuda docs](https://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__STREAM.html#group__CUDA__STREAM_1g6a898b652dfc6aa1d5c8d97062618b2f)
pub fn wait(&self, event: &CudaEvent) -> Result<(), DriverError> {
if self.ctx != event.ctx {
return Err(DriverError(sys::cudaError_enum::CUDA_ERROR_INVALID_CONTEXT));
}
self.ctx.bind_to_thread()?;
unsafe {
result::stream::wait_event(
self.cu_stream,
event.cu_event,
sys::CUevent_wait_flags::CU_EVENT_WAIT_DEFAULT,
)
}
}
/// Ensures this stream waits for the current workload in `other` to complete.
/// This is shorthand for `self.wait(other.record_event())`
pub fn join(&self, other: &CudaStream) -> Result<(), DriverError> {
self.wait(&other.record_event(None)?)
}
}
/// `Vec<T>` on a cuda device. You can allocate and modify this with [CudaStream].
///
/// This object is thread safe.
#[derive(Debug)]
pub struct CudaSlice<T> {
pub(crate) cu_device_ptr: sys::CUdeviceptr,
pub(crate) len: usize,
pub(crate) read: Option<CudaEvent>,
pub(crate) write: Option<CudaEvent>,
pub(crate) stream: Arc<CudaStream>,
pub(crate) marker: PhantomData<*const T>,
}
unsafe impl<T> Send for CudaSlice<T> {}
unsafe impl<T> Sync for CudaSlice<T> {}
impl<T> Drop for CudaSlice<T> {
fn drop(&mut self) {
let ctx = &self.stream.ctx;
if let Some(read) = self.read.as_ref() {
ctx.record_err(self.stream.wait(read));
}
if let Some(write) = self.write.as_ref() {
ctx.record_err(self.stream.wait(write));
}
ctx.record_err(unsafe { result::free_async(self.cu_device_ptr, self.stream.cu_stream) });
}
}
impl<T> CudaSlice<T> {
/// The number of elements of `T` in this object.
pub fn len(&self) -> usize {
self.len
}
/// The number of bytes in this object.
pub fn num_bytes(&self) -> usize {
self.len * std::mem::size_of::<T>()
}
/// True if there are no elements in the object.
pub fn is_empty(&self) -> bool {
self.len == 0
}
/// The device ordinal this belongs to
pub fn ordinal(&self) -> usize {
self.stream.ctx.ordinal
}
/// The context this belongs to
pub fn context(&self) -> &Arc<CudaContext> {
&self.stream.ctx
}
/// The stream this object was allocated on and later will be dropped on.
pub fn stream(&self) -> &Arc<CudaStream> {
&self.stream
}
}
impl<T: DeviceRepr> CudaSlice<T> {
/// Allocates copy of self and schedules a device to device copy of memory.
pub fn try_clone(&self) -> Result<Self, result::DriverError> {
self.stream.clone_dtod(self)
}
}
impl<T: DeviceRepr> Clone for CudaSlice<T> {
fn clone(&self) -> Self {
self.try_clone().unwrap()
}
}
impl<T: Clone + Default + DeviceRepr> TryFrom<CudaSlice<T>> for Vec<T> {
type Error = result::DriverError;
fn try_from(value: CudaSlice<T>) -> Result<Self, Self::Error> {
value.stream.memcpy_dtov(&value)
}
}
/// `&[T]` on a cuda device. An immutable sub-view into a [CudaSlice] created by [CudaSlice::as_view()]/[CudaSlice::slice()].
#[derive(Debug)]
pub struct CudaView<'a, T> {
pub(crate) ptr: sys::CUdeviceptr,
pub(crate) len: usize,
pub(crate) read: &'a Option<CudaEvent>,
pub(crate) write: &'a Option<CudaEvent>,
pub(crate) stream: &'a Arc<CudaStream>,
marker: PhantomData<&'a [T]>,
}
impl<T> CudaSlice<T> {
pub fn as_view(&self) -> CudaView<'_, T> {
CudaView {
ptr: self.cu_device_ptr,
len: self.len,
read: &self.read,
write: &self.write,
stream: &self.stream,
marker: PhantomData,
}
}
}
impl<T> CudaView<'_, T> {
/// The number of elements `T` in this view.
pub fn len(&self) -> usize {
self.len
}
pub fn is_empty(&self) -> bool {
self.len == 0
}
fn resize(&self, start: usize, end: usize) -> Self {
assert!(start <= end && end <= self.len);
Self {
ptr: self.ptr + (start * std::mem::size_of::<T>()) as u64,
len: end - start,
read: self.read,
write: self.write,
stream: self.stream,
marker: PhantomData,
}
}
}
/// `&mut [T]` on a cuda device. A mutable sub-view into a [CudaSlice] created by [CudaSlice::as_view_mut()]/[CudaSlice::slice_mut()].
#[derive(Debug)]
pub struct CudaViewMut<'a, T> {
pub(crate) ptr: sys::CUdeviceptr,
pub(crate) len: usize,
pub(crate) read: &'a Option<CudaEvent>,
pub(crate) write: &'a Option<CudaEvent>,
pub(crate) stream: &'a Arc<CudaStream>,
marker: PhantomData<&'a mut [T]>,
}
impl<T> CudaSlice<T> {
pub fn as_view_mut(&mut self) -> CudaViewMut<'_, T> {
CudaViewMut {
ptr: self.cu_device_ptr,
len: self.len,
read: &self.read,
write: &self.write,
stream: &self.stream,
marker: PhantomData,
}
}
}
impl<T> CudaViewMut<'_, T> {
/// Number of elements `T` that are in this view.
pub fn len(&self) -> usize {
self.len
}
pub fn is_empty(&self) -> bool {
self.len == 0
}
/// Downgrade this to a `&[T]`
pub fn as_view(&self) -> CudaView<'_, T> {
CudaView {
ptr: self.ptr,
len: self.len,
read: self.read,
write: self.write,
stream: self.stream,
marker: PhantomData,
}
}
fn resize(&self, start: usize, end: usize) -> Self {
Self {
ptr: self.ptr + (start * std::mem::size_of::<T>()) as u64,
len: end - start,
read: self.read,
write: self.write,
stream: self.stream,
marker: PhantomData,
}
}
}
/// Marker trait to indicate that the type is valid
/// when all of its bits are set to 0.
///
/// # Safety
/// Not all types are valid when all bits are set to 0.
/// Be very sure when implementing this trait!
pub unsafe trait ValidAsZeroBits {}
unsafe impl ValidAsZeroBits for bool {}
unsafe impl ValidAsZeroBits for i8 {}
unsafe impl ValidAsZeroBits for i16 {}
unsafe impl ValidAsZeroBits for i32 {}
unsafe impl ValidAsZeroBits for i64 {}
unsafe impl ValidAsZeroBits for i128 {}
unsafe impl ValidAsZeroBits for isize {}
unsafe impl ValidAsZeroBits for u8 {}
unsafe impl ValidAsZeroBits for u16 {}
unsafe impl ValidAsZeroBits for u32 {}
unsafe impl ValidAsZeroBits for u64 {}
unsafe impl ValidAsZeroBits for u128 {}
unsafe impl ValidAsZeroBits for usize {}
unsafe impl ValidAsZeroBits for f32 {}
unsafe impl ValidAsZeroBits for f64 {}
#[cfg(feature = "f16")]
unsafe impl ValidAsZeroBits for half::f16 {}
#[cfg(feature = "f16")]
unsafe impl ValidAsZeroBits for half::bf16 {}
unsafe impl<T: ValidAsZeroBits, const M: usize> ValidAsZeroBits for [T; M] {}
/// Implement `ValidAsZeroBits` for tuples if all elements are `ValidAsZeroBits`,
///
/// # Note
/// This will also implement `ValidAsZeroBits` for a tuple with one element
macro_rules! impl_tuples {
($t:tt) => {
impl_tuples!(@ $t);
};
// the $l is in front of the reptition to prevent parsing ambiguities
($l:tt $(,$t:tt)+) => {
impl_tuples!($($t),+);
impl_tuples!(@ $l $(,$t)+);
};
(@ $($t:tt),+) => {
unsafe impl<$($t: ValidAsZeroBits,)+> ValidAsZeroBits for ($($t,)+) {}
};
}
impl_tuples!(A, B, C, D, E, F, G, H, I, J, K, L);
/// Something that can be copied to device memory and
/// turned into a parameter for [result::launch_kernel].
///
/// # Safety
///
/// This is unsafe because a struct should likely
/// be `#[repr(C)]` to be represented in cuda memory,
/// and not all types are valid.
pub unsafe trait DeviceRepr {}
unsafe impl DeviceRepr for bool {}
unsafe impl DeviceRepr for i8 {}
unsafe impl DeviceRepr for i16 {}
unsafe impl DeviceRepr for i32 {}
unsafe impl DeviceRepr for i64 {}
unsafe impl DeviceRepr for i128 {}
unsafe impl DeviceRepr for isize {}
unsafe impl DeviceRepr for u8 {}
unsafe impl DeviceRepr for u16 {}
unsafe impl DeviceRepr for u32 {}
unsafe impl DeviceRepr for u64 {}
unsafe impl DeviceRepr for u128 {}
unsafe impl DeviceRepr for usize {}
unsafe impl DeviceRepr for f32 {}
unsafe impl DeviceRepr for f64 {}
#[cfg(feature = "f16")]
unsafe impl DeviceRepr for half::f16 {}
#[cfg(feature = "f16")]
unsafe impl DeviceRepr for half::bf16 {}
#[cfg(feature = "f8")]
unsafe impl DeviceRepr for float8::F8E4M3 {}
#[cfg(feature = "f8")]
unsafe impl ValidAsZeroBits for float8::F8E4M3 {}
#[cfg(feature = "f8")]
unsafe impl DeviceRepr for float8::F8E5M2 {}
#[cfg(feature = "f8")]
unsafe impl ValidAsZeroBits for float8::F8E5M2 {}
#[cfg(feature = "f4")]
unsafe impl DeviceRepr for float4::F4E2M1 {}
#[cfg(feature = "f4")]
unsafe impl ValidAsZeroBits for float4::F4E2M1 {}
#[cfg(feature = "f4")]
unsafe impl DeviceRepr for float4::E8M0 {}
#[cfg(feature = "f4")]
unsafe impl ValidAsZeroBits for float4::E8M0 {}
/// Base trait for abstracting over [CudaSlice]/[CudaView]/[CudaViewMut].
///
/// Don't use this directly - use [DevicePtr]/[DevicePtrMut].
pub trait DeviceSlice<T> {
fn len(&self) -> usize;
fn num_bytes(&self) -> usize {
self.len() * std::mem::size_of::<T>()
}
fn is_empty(&self) -> bool {
self.len() == 0
}
fn stream(&self) -> &Arc<CudaStream>;
}
impl<T> DeviceSlice<T> for CudaSlice<T> {
fn len(&self) -> usize {
self.len
}
fn stream(&self) -> &Arc<CudaStream> {
&self.stream
}
}
impl<T> DeviceSlice<T> for CudaView<'_, T> {
fn len(&self) -> usize {
self.len
}
fn stream(&self) -> &Arc<CudaStream> {
self.stream
}
}
impl<T> DeviceSlice<T> for CudaViewMut<'_, T> {
fn len(&self) -> usize {
self.len
}
fn stream(&self) -> &Arc<CudaStream> {
self.stream
}
}
/// A synchronization primitive to enable stream & event synchronization.
/// Primarily used with [DevicePtr] and [DevicePtrMut]
#[derive(Debug)]
#[must_use]
pub enum SyncOnDrop<'a> {
/// Will record the stream's workload to the event on drop.
Record(Option<(&'a CudaEvent, &'a CudaStream)>),
/// Will call stream synchronize on drop.
Sync(Option<&'a CudaStream>),
}
impl<'a> SyncOnDrop<'a> {
/// Construct a [SyncOnDrop::Record] variant
pub fn record_event(event: &'a Option<CudaEvent>, stream: &'a CudaStream) -> Self {
SyncOnDrop::Record(event.as_ref().map(|e| (e, stream)))
}
/// Construct a [SyncOnDrop::Sync] variant
pub fn sync_stream(stream: &'a CudaStream) -> Self {
SyncOnDrop::Sync(Some(stream))
}
}
impl Drop for SyncOnDrop<'_> {
fn drop(&mut self) {
match self {
SyncOnDrop::Record(target) => {
if let Some((event, stream)) = std::mem::take(target) {
stream.ctx.record_err(event.record(stream));
}
}
SyncOnDrop::Sync(target) => {
if let Some(stream) = std::mem::take(target) {
stream.ctx.record_err(stream.synchronize());
}
}
}
}
}
/// Abstraction over [CudaSlice]/[CudaView]
pub trait DevicePtr<T>: DeviceSlice<T> {
/// Retrieve the device pointer with the intent to read the device memory
/// associated with it.
///
/// Implementations of this method should ensure `stream` waits for any previous
/// writes of this memory before continuing (do not need to wait for any previous reads).
///
/// The [SyncOnDrop] item of the return tuple should be dropped **after** the read of
/// the [sys::CUdeviceptr] is scheduled.
///
/// In most cases you can use like:
/// ```ignore
/// let (src, _record_src) = src.device_ptr(&stream);
/// ```
/// Which will drop the [SyncOnDrop] at the end of the scope.
fn device_ptr<'a>(&'a self, stream: &'a CudaStream) -> (sys::CUdeviceptr, SyncOnDrop<'a>);
}
impl<T> DevicePtr<T> for CudaSlice<T> {
fn device_ptr<'a>(&'a self, stream: &'a CudaStream) -> (sys::CUdeviceptr, SyncOnDrop<'a>) {
if self.stream.context().is_managing_stream_synchronization() {
if let Some(write) = self.write.as_ref() {
stream.ctx.record_err(stream.wait(write));
}
}
(
self.cu_device_ptr,
SyncOnDrop::record_event(&self.read, stream),
)
}
}
impl<T> DevicePtr<T> for CudaView<'_, T> {
fn device_ptr<'a>(&'a self, stream: &'a CudaStream) -> (sys::CUdeviceptr, SyncOnDrop<'a>) {
if self.stream.context().is_managing_stream_synchronization() {
if let Some(write) = self.write.as_ref() {
stream.ctx.record_err(stream.wait(write));
}
}
(self.ptr, SyncOnDrop::record_event(self.read, stream))
}
}
impl<T> DevicePtr<T> for CudaViewMut<'_, T> {
fn device_ptr<'a>(&'a self, stream: &'a CudaStream) -> (sys::CUdeviceptr, SyncOnDrop<'a>) {
if self.stream.context().is_managing_stream_synchronization() {
if let Some(write) = self.write.as_ref() {
stream.ctx.record_err(stream.wait(write));
}
}
(self.ptr, SyncOnDrop::record_event(self.read, stream))
}
}
/// Abstraction over [CudaSlice]/[CudaViewMut]
pub trait DevicePtrMut<T>: DeviceSlice<T> {
/// Retrieve the device pointer with the intent to modify the device memory
/// associated with it.
///
/// Implementations of this method should ensure `stream` waits for any previous
/// reads/writes of this memory before continuing.
///
/// The [SyncOnDrop] item of the return tuple should be dropped **after** the write of
/// the [sys::CUdeviceptr] is scheduled.
///
/// In most cases you can use like:
/// ```ignore
/// let (src, _record_src) = src.device_ptr_mut(&stream);
/// ```
/// Which will drop the [SyncOnDrop] at the end of the scope.
fn device_ptr_mut<'a>(
&'a mut self,
stream: &'a CudaStream,
) -> (sys::CUdeviceptr, SyncOnDrop<'a>);
}
impl<T> DevicePtrMut<T> for CudaSlice<T> {
fn device_ptr_mut<'a>(
&'a mut self,
stream: &'a CudaStream,
) -> (sys::CUdeviceptr, SyncOnDrop<'a>) {
if self.stream.context().is_managing_stream_synchronization() {
if let Some(read) = self.read.as_ref() {
stream.ctx.record_err(stream.wait(read));
}
if let Some(write) = self.write.as_ref() {
stream.ctx.record_err(stream.wait(write));
}
}
(
self.cu_device_ptr,
SyncOnDrop::record_event(&self.write, stream),
)
}
}
impl<T> DevicePtrMut<T> for CudaViewMut<'_, T> {
fn device_ptr_mut<'a>(
&'a mut self,
stream: &'a CudaStream,
) -> (sys::CUdeviceptr, SyncOnDrop<'a>) {
if self.stream.context().is_managing_stream_synchronization() {
if let Some(read) = self.read.as_ref() {
stream.ctx.record_err(stream.wait(read));
}
if let Some(write) = self.write.as_ref() {
stream.ctx.record_err(stream.wait(write));
}
}
(self.ptr, SyncOnDrop::record_event(self.write, stream))
}
}
/// Abstraction over `&[T]`, `&Vec<T>` and [`PinnedHostSlice<T>`].
pub trait HostSlice<T> {
fn len(&self) -> usize;
fn is_empty(&self) -> bool {
self.len() == 0
}
/// # Safety
/// This is **only** safe if the resulting slice is used with `stream`. Otherwise
/// You may run into device synchronization errors
unsafe fn stream_synced_slice<'a>(
&'a self,
stream: &'a CudaStream,
) -> (&'a [T], SyncOnDrop<'a>);
/// # Safety
/// This is **only** safe if the resulting slice is used with `stream`. Otherwise
/// You may run into device synchronization errors
unsafe fn stream_synced_mut_slice<'a>(
&'a mut self,
stream: &'a CudaStream,
) -> (&'a mut [T], SyncOnDrop<'a>);
}
impl<T, const N: usize> HostSlice<T> for [T; N] {
fn len(&self) -> usize {
N
}
unsafe fn stream_synced_slice<'a>(
&'a self,
_stream: &'a CudaStream,
) -> (&'a [T], SyncOnDrop<'a>) {
(self, SyncOnDrop::Sync(None))
}
unsafe fn stream_synced_mut_slice<'a>(
&'a mut self,
_stream: &'a CudaStream,