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
use crate::driver::{result, sys};
use super::{alloc::DeviceRepr, device_ptr::DeviceSlice};
use std::{
marker::PhantomData,
ops::{Bound, RangeBounds},
string::String,
};
#[cfg(feature = "no-std")]
use spin::RwLock;
#[cfg(not(feature = "no-std"))]
use std::sync::RwLock;
use std::{collections::BTreeMap, marker::Unpin, pin::Pin, sync::Arc, vec::Vec};
/// A wrapper around [sys::CUdevice], [sys::CUcontext], [sys::CUstream],
/// and [CudaFunction].
///
/// ```rust
/// # use cudarc::driver::CudaDevice;
/// let dev = CudaDevice::new(0).unwrap();
/// ```
///
/// # Safety
/// 1. impl [Drop] to call all the corresponding resource cleanup methods
/// 2. Doesn't impl clone, so you can't have multiple device pointers
/// hanging around.
/// 3. Any allocations enforce that self is an [Arc], meaning no allocation
/// can outlive the [CudaDevice]
#[derive(Debug)]
pub struct CudaDevice {
pub(crate) cu_device: sys::CUdevice,
pub(crate) cu_primary_ctx: sys::CUcontext,
/// The stream that all work is executed on.
pub(crate) stream: sys::CUstream,
/// Used to synchronize with stream
pub(crate) event: sys::CUevent,
pub(crate) modules: RwLock<BTreeMap<String, CudaModule>>,
pub(crate) ordinal: usize,
}
unsafe impl Send for CudaDevice {}
unsafe impl Sync for CudaDevice {}
impl CudaDevice {
/// Creates a new [CudaDevice] on device index `ordinal`.
pub fn new(ordinal: usize) -> Result<Arc<Self>, result::DriverError> {
result::init().unwrap();
let cu_device = result::device::get(ordinal as i32).unwrap();
// primary context initialization, can fail with OOM
let cu_primary_ctx = unsafe { result::primary_ctx::retain(cu_device) }?;
unsafe { result::ctx::set_current(cu_primary_ctx) }.unwrap();
// can fail with OOM
let event = result::event::create(sys::CUevent_flags::CU_EVENT_DISABLE_TIMING)?;
let device = CudaDevice {
cu_device,
cu_primary_ctx,
stream: std::ptr::null_mut(),
event,
modules: RwLock::new(BTreeMap::new()),
ordinal,
};
Ok(Arc::new(device))
}
/// Get the `ordinal` index of this [CudaDevice].
pub fn ordinal(&self) -> usize {
self.ordinal
}
/// Get the underlying [sys::CUdevice] of this [CudaDevice].
///
/// # 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 [CudaDevice].
pub fn cu_device(&self) -> &sys::CUdevice {
&self.cu_device
}
/// Get the underlying [sys::CUcontext] of this [CudaDevice].
///
/// # 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 [CudaDevice].
pub fn cu_primary_ctx(&self) -> &sys::CUcontext {
&self.cu_primary_ctx
}
/// Get the underlying [sys::CUstream] that this [CudaDevice] executes
/// all of its work on.
///
/// # Safety
/// While this function is marked as safe, actually using the
/// returned object is unsafe.
///
/// **You must not free/release the stream pointer**, as it is still
/// owned by the [CudaDevice].
pub fn cu_stream(&self) -> &sys::CUstream {
&self.stream
}
}
impl Drop for CudaDevice {
fn drop(&mut self) {
let modules = RwLock::get_mut(&mut self.modules);
#[cfg(not(feature = "no-std"))]
let modules = modules.unwrap();
for (_, module) in modules.iter() {
unsafe { result::module::unload(module.cu_module) }.unwrap();
}
modules.clear();
let stream = std::mem::replace(&mut self.stream, std::ptr::null_mut());
if !stream.is_null() {
unsafe { result::stream::destroy(stream) }.unwrap();
}
let event = std::mem::replace(&mut self.event, std::ptr::null_mut());
if !event.is_null() {
unsafe { result::event::destroy(event) }.unwrap();
}
let ctx = std::mem::replace(&mut self.cu_primary_ctx, std::ptr::null_mut());
if !ctx.is_null() {
unsafe { result::primary_ctx::release(self.cu_device) }.unwrap();
}
}
}
/// Contains a reference counted pointer to both
/// device and host memory allocated for type `T`.
///
/// # Host data
///
/// *This owns the host data it is associated with*. However
/// it is possible to create device memory without having
/// a corresponding host memory, so the host memory is
/// actually [Option].
///
/// # Reclaiming host data
///
/// To reclaim the host data for this device data,
/// use [CudaDevice::sync_reclaim()]. This will
/// perform necessary synchronization to ensure
/// that the device data finishes copying over.
///
/// # Mutating device data
///
/// This can only be done by launching kernels via
/// [crate::driver::LaunchAsync] which is implemented
/// by [CudaDevice]. Pass `&mut CudaSlice<T>`
/// if you want to mutate the rc, and `&CudaSlice<T>` otherwise.
///
/// Unfortunately, `&CudaSlice<T>` can **still be mutated
/// by the [CudaFunction]**.
#[derive(Debug)]
pub struct CudaSlice<T> {
pub(crate) cu_device_ptr: sys::CUdeviceptr,
pub(crate) len: usize,
pub(crate) device: Arc<CudaDevice>,
pub(crate) host_buf: Option<Pin<Vec<T>>>,
}
unsafe impl<T: Send> Send for CudaSlice<T> {}
unsafe impl<T: Sync> Sync for CudaSlice<T> {}
impl<T> Drop for CudaSlice<T> {
fn drop(&mut self) {
unsafe {
result::free_async(self.cu_device_ptr, self.device.stream).unwrap();
}
}
}
impl<T> CudaSlice<T> {
/// Get a clone of the underlying [CudaDevice].
pub fn device(&self) -> Arc<CudaDevice> {
self.device.clone()
}
}
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> {
let mut dst = unsafe { self.device.alloc(self.len) }?;
self.device.dtod_copy(self, &mut dst)?;
Ok(dst)
}
}
impl<T: DeviceRepr> Clone for CudaSlice<T> {
fn clone(&self) -> Self {
self.try_clone().unwrap()
}
}
impl<T: Clone + Default + DeviceRepr + Unpin> TryFrom<CudaSlice<T>> for Vec<T> {
type Error = result::DriverError;
fn try_from(value: CudaSlice<T>) -> Result<Self, Self::Error> {
value.device.clone().sync_reclaim(value)
}
}
/// Wrapper around [sys::CUmodule] that also contains
/// the loaded [CudaFunction] associated with this module.
///
/// See [CudaModule::get_fn()] for retrieving function handles.
#[derive(Debug)]
pub(crate) struct CudaModule {
pub(crate) cu_module: sys::CUmodule,
pub(crate) functions: BTreeMap<&'static str, sys::CUfunction>,
}
unsafe impl Send for CudaModule {}
unsafe impl Sync for CudaModule {}
/// Wrapper around [sys::CUfunction]. Used by [crate::driver::LaunchAsync].
#[derive(Debug, Clone)]
pub struct CudaFunction {
pub(crate) cu_function: sys::CUfunction,
pub(crate) device: Arc<CudaDevice>,
}
unsafe impl Send for CudaFunction {}
unsafe impl Sync for CudaFunction {}
/// A wrapper around [sys::CUstream] that safely ensures null stream is synchronized
/// upon the completion of this streams work.
///
/// Create with [CudaDevice::fork_default_stream].
///
/// The synchronization happens in **code order**. E.g.
/// ```ignore
/// let stream = dev.fork_default_stream()?; // 0
/// dev.launch(...)?; // 1
/// dev.launch_on_stream(&stream, ...)?; // 2
/// dev.launch(...)?; // 3
/// drop(stream); // 4
/// dev.launch(...) // 5
/// ```
///
/// - 0 will place a streamWaitEvent(default work stream) on the new stream
/// - 1 will launch on the default work stream
/// - 2 will launch concurrently to 1 on `&stream`,
/// - 3 will launch after 1 on the default work stream, but potentially concurrently to 2.
/// - 4 will place a streamWaitEvent(`&stream`) on default work stream
/// - 5 will happen on the default stream **after the default stream waits for 2**
#[derive(Debug)]
pub struct CudaStream {
pub stream: sys::CUstream,
device: Arc<CudaDevice>,
}
impl CudaDevice {
/// Allocates a new stream that can execute kernels concurrently to the default stream.
///
/// The synchronization with default stream happens in **code order**. See [CudaStream] docstring.
///
/// This stream synchronizes in the following way:
/// 1. On creation it adds a wait for any existing work on the default work stream to complete
/// 2. On drop it adds a wait for any existign work on Self to complete *to the default stream*.
pub fn fork_default_stream(self: &Arc<Self>) -> Result<CudaStream, result::DriverError> {
let stream = CudaStream {
stream: result::stream::create(result::stream::StreamKind::NonBlocking)?,
device: self.clone(),
};
stream.wait_for_default()?;
Ok(stream)
}
/// Forces [CudaStream] to drop, causing the default work stream to block on `streams` completion.
/// **This is asynchronous with respect to the host.**
#[allow(unused_variables)]
pub fn wait_for(self: &Arc<Self>, stream: &CudaStream) -> Result<(), result::DriverError> {
unsafe {
result::event::record(self.event, stream.stream)?;
result::stream::wait_event(
self.stream,
self.event,
sys::CUevent_wait_flags::CU_EVENT_WAIT_DEFAULT,
)
}
}
}
impl CudaStream {
/// Record's the current default streams workload, and then causes `self`
/// to wait for the default stream to finish that recorded workload.
pub fn wait_for_default(&self) -> Result<(), result::DriverError> {
unsafe {
result::event::record(self.device.event, self.device.stream)?;
result::stream::wait_event(
self.stream,
self.device.event,
sys::CUevent_wait_flags::CU_EVENT_WAIT_DEFAULT,
)
}
}
}
impl Drop for CudaStream {
fn drop(&mut self) {
self.device.wait_for(self).unwrap();
unsafe {
result::stream::destroy(self.stream).unwrap();
}
}
}
/// A immutable sub-view into a [CudaSlice] created by [CudaSlice::try_slice()].
#[derive(Debug)]
pub struct CudaView<'a, T> {
pub(crate) root: &'a sys::CUdeviceptr,
pub(crate) ptr: sys::CUdeviceptr,
pub(crate) len: usize,
marker: PhantomData<T>,
}
impl<T> CudaSlice<T> {
/// Creates a [CudaView] at the specified offset from the start of `self`.
///
/// Returns `None` if `range.start >= self.len`
pub fn slice(&self, range: impl RangeBounds<usize>) -> CudaView<'_, T> {
self.try_slice(range).unwrap()
}
/// Fallible version of [CudaSlice::slice]
pub fn try_slice(&self, range: impl RangeBounds<usize>) -> Option<CudaView<'_, T>> {
range.bounds(..self.len()).map(|(start, end)| CudaView {
root: &self.cu_device_ptr,
ptr: self.cu_device_ptr + (start * std::mem::size_of::<T>()) as u64,
len: end - start,
marker: PhantomData,
})
}
/// Reinterprets the slice of memory into a different type. `len` is the number
/// of elements of the new type `S` that are expected. If not enough bytes
/// are allocated in `self` for the view, then this returns `None`.
///
/// # Safety
/// This is unsafe because not the memory for the view may not be a valid interpretation
/// for the type `S`.
pub unsafe fn transmute<S>(&self, len: usize) -> Option<CudaView<'_, S>> {
(len * std::mem::size_of::<S>() <= self.num_bytes()).then_some(CudaView {
root: &self.cu_device_ptr,
ptr: self.cu_device_ptr,
len,
marker: PhantomData,
})
}
}
impl<'a, T> CudaView<'a, T> {
/// Creates a [CudaView] at the specified offset from the start of `self`.
///
/// Returns `None` if `range.start >= self.len`
pub fn slice(&self, range: impl RangeBounds<usize>) -> CudaView<'a, T> {
self.try_slice(range).unwrap()
}
/// Fallible version of [CudaView::slice]
pub fn try_slice(&self, range: impl RangeBounds<usize>) -> Option<CudaView<'a, T>> {
range.bounds(..self.len()).map(|(start, end)| CudaView {
root: self.root,
ptr: self.ptr + (start * std::mem::size_of::<T>()) as u64,
len: end - start,
marker: PhantomData,
})
}
}
/// A mutable sub-view into a [CudaSlice] created by [CudaSlice::try_slice_mut()].
#[derive(Debug)]
pub struct CudaViewMut<'a, T> {
pub(crate) root: &'a mut sys::CUdeviceptr,
pub(crate) ptr: sys::CUdeviceptr,
pub(crate) len: usize,
marker: PhantomData<T>,
}
impl<T> CudaSlice<T> {
/// Creates a [CudaViewMut] at the specified offset from the start of `self`.
///
/// Returns `None` if `offset >= self.len`
pub fn slice_mut(&mut self, range: impl RangeBounds<usize>) -> CudaViewMut<'_, T> {
self.try_slice_mut(range).unwrap()
}
/// Fallible version of [CudaSlice::slice_mut]
pub fn try_slice_mut(&mut self, range: impl RangeBounds<usize>) -> Option<CudaViewMut<'_, T>> {
range.bounds(..self.len()).map(|(start, end)| CudaViewMut {
ptr: self.cu_device_ptr + (start * std::mem::size_of::<T>()) as u64,
root: &mut self.cu_device_ptr,
len: end - start,
marker: PhantomData,
})
}
/// Reinterprets the slice of memory into a different type. `len` is the number
/// of elements of the new type `S` that are expected. If not enough bytes
/// are allocated in `self` for the view, then this returns `None`.
///
/// # Safety
/// This is unsafe because not the memory for the view may not be a valid interpretation
/// for the type `S`.
pub unsafe fn transmute_mut<S>(&mut self, len: usize) -> Option<CudaViewMut<'_, S>> {
(len * std::mem::size_of::<S>() <= self.num_bytes()).then_some(CudaViewMut {
ptr: self.cu_device_ptr,
root: &mut self.cu_device_ptr,
len,
marker: PhantomData,
})
}
}
impl<'a, T> CudaViewMut<'a, T> {
/// Creates a [CudaView] at the specified offset from the start of `self`.
///
/// Returns `None` if `range.start >= self.len`
pub fn slice<'b: 'a>(&'b self, range: impl RangeBounds<usize>) -> CudaView<'a, T> {
self.try_slice(range).unwrap()
}
/// Fallible version of [CudaViewMut::slice]
pub fn try_slice<'b: 'a>(&'b self, range: impl RangeBounds<usize>) -> Option<CudaView<'a, T>> {
range.bounds(..self.len()).map(|(start, end)| CudaView {
root: self.root,
ptr: self.ptr + (start * std::mem::size_of::<T>()) as u64,
len: end - start,
marker: PhantomData,
})
}
/// Creates a [CudaViewMut] at the specified offset from the start of `self`.
///
/// Returns `None` if `offset >= self.len`
pub fn slice_mut<'b: 'a>(&'b mut self, range: impl RangeBounds<usize>) -> CudaViewMut<'a, T> {
self.try_slice_mut(range).unwrap()
}
/// Fallible version of [CudaViewMut::slice_mut]
pub fn try_slice_mut<'b: 'a>(
&'b mut self,
range: impl RangeBounds<usize>,
) -> Option<CudaViewMut<'a, T>> {
range.bounds(..self.len()).map(|(start, end)| CudaViewMut {
ptr: self.ptr + (start * std::mem::size_of::<T>()) as u64,
root: self.root,
len: end - start,
marker: PhantomData,
})
}
}
trait RangeHelper: RangeBounds<usize> {
fn inclusive_start(&self, valid_start: usize) -> usize;
fn exclusive_end(&self, valid_end: usize) -> usize;
fn bounds(&self, valid: impl RangeHelper) -> Option<(usize, usize)> {
let vs = valid.inclusive_start(0);
let ve = valid.exclusive_end(usize::MAX);
let s = self.inclusive_start(vs);
let e = self.exclusive_end(ve);
let inside = s >= vs && e <= ve;
let valid = s < e || (s == e && !matches!(self.end_bound(), Bound::Included(_)));
(inside && valid).then_some((s, e))
}
}
impl<R: RangeBounds<usize>> RangeHelper for R {
fn inclusive_start(&self, valid_start: usize) -> usize {
match self.start_bound() {
Bound::Included(n) => *n,
Bound::Excluded(n) => *n + 1,
Bound::Unbounded => valid_start,
}
}
fn exclusive_end(&self, valid_end: usize) -> usize {
match self.end_bound() {
Bound::Included(n) => *n + 1,
Bound::Excluded(n) => *n,
Bound::Unbounded => valid_end,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[allow(clippy::reversed_empty_ranges)]
fn test_bounds_helper() {
assert_eq!((..2usize).bounds(0..usize::MAX), Some((0, 2)));
assert_eq!((1..2usize).bounds(..usize::MAX), Some((1, 2)));
assert_eq!((..).bounds(1..10), Some((1, 10)));
assert_eq!((2..=2usize).bounds(0..usize::MAX), Some((2, 3)));
assert_eq!((2..=2usize).bounds(0..=1), None);
assert_eq!((2..2usize).bounds(0..usize::MAX), Some((2, 2)));
assert_eq!((1..0usize).bounds(0..usize::MAX), None);
assert_eq!((1..=0usize).bounds(0..usize::MAX), None);
}
#[test]
fn test_transmutes() {
let dev = CudaDevice::new(0).unwrap();
let mut slice = dev.alloc_zeros::<u8>(100).unwrap();
assert!(unsafe { slice.transmute::<f32>(25) }.is_some());
assert!(unsafe { slice.transmute::<f32>(26) }.is_none());
assert!(unsafe { slice.transmute_mut::<f32>(25) }.is_some());
assert!(unsafe { slice.transmute_mut::<f32>(26) }.is_none());
}
}