use cudarc::driver::safe::CudaGraph as CudarcGraph;
use cudarc::driver::sys::{CUgraphInstantiate_flags, CUstreamCaptureMode};
use super::GuardedStream;
use super::lock::CapturePermit;
use crate::error::Result;
use crate::runtime::common::Allocator;
use crate::runtime::cuda::allocator::CudaAllocator;
pub(crate) const INSTANTIATE_FLAGS: CUgraphInstantiate_flags =
CUgraphInstantiate_flags::CUDA_GRAPH_INSTANTIATE_FLAG_AUTO_FREE_ON_LAUNCH;
pub(crate) struct CaptureSession<'a> {
_permit: CapturePermit<'a>,
stream: &'a GuardedStream,
allocator: &'a CudaAllocator,
capturing: bool,
frozen: bool,
}
impl<'a> CaptureSession<'a> {
pub(crate) fn begin(
stream: &'a GuardedStream,
allocator: &'a CudaAllocator,
setup: impl FnOnce() -> Result<()>,
) -> Result<Self> {
let permit = CapturePermit::acquire(stream.capture_lock(), stream.device_index())?;
setup()?;
let mut session = Self {
_permit: permit,
stream,
allocator,
capturing: false,
frozen: false,
};
session.allocator.freeze();
session.frozen = true;
session
.stream
.raw()
.begin_capture(CUstreamCaptureMode::CU_STREAM_CAPTURE_MODE_GLOBAL)?;
session.capturing = true;
Ok(session)
}
pub(crate) fn end(mut self) -> (Result<Option<CudarcGraph>>, Option<usize>) {
let graph = self.stream.arc().end_capture(INSTANTIATE_FLAGS);
self.capturing = false;
let arena_bytes_used = self.allocator.arena_high_water();
self.allocator.unfreeze();
self.frozen = false;
(graph.map_err(Into::into), arena_bytes_used)
}
}
impl Drop for CaptureSession<'_> {
fn drop(&mut self) {
if self.capturing {
let _ = self.stream.arc().end_capture(INSTANTIATE_FLAGS);
}
if self.frozen {
self.allocator.unfreeze();
}
}
}