use std::{
cell::RefCell, collections::HashMap, hash::Hash, marker::PhantomData, mem, panic, ptr,
sync::Arc,
};
use num_enum::{IntoPrimitive, TryFromPrimitive};
use singe_core::{impl_enum_display, report_cleanup_failure};
use singe_cuda_sys::runtime;
use super::{AsStream, Stream};
use crate::{
error::{Error, Result},
graph::{ExecutableGraph, Graph, GraphDependency, GraphInstantiateFlags},
module::{CodeOwnerId, Module},
try_ffi,
};
singe_core::native_enum! {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, TryFromPrimitive, IntoPrimitive)]
#[repr(u32)]
#[non_exhaustive]
pub enum StreamCaptureStatus: runtime::cudaStreamCaptureStatus {
None = CU_STREAM_CAPTURE_STATUS_NONE,
Active = CU_STREAM_CAPTURE_STATUS_ACTIVE,
Invalidated = CU_STREAM_CAPTURE_STATUS_INVALIDATED,
}
}
singe_core::native_enum! {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, TryFromPrimitive, IntoPrimitive)]
#[repr(u32)]
#[non_exhaustive]
pub enum StreamCaptureMode: runtime::cudaStreamCaptureMode {
Global = CU_STREAM_CAPTURE_MODE_GLOBAL,
ThreadLocal = CU_STREAM_CAPTURE_MODE_THREAD_LOCAL,
Relaxed = CU_STREAM_CAPTURE_MODE_RELAXED,
}
}
singe_core::native_enum! {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, TryFromPrimitive, IntoPrimitive)]
#[repr(u32)]
#[non_exhaustive]
pub enum StreamCaptureDependencyUpdate: runtime::cudaStreamUpdateCaptureDependenciesFlags {
Add = cudaStreamAddCaptureDependencies,
Set = cudaStreamSetCaptureDependencies,
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct StreamCaptureInfo {
pub status: StreamCaptureStatus,
pub id: u64,
}
#[derive(Debug)]
pub struct StreamCaptureScope<'scope> {
stream: &'scope Stream,
modules: RefCell<HashMap<CodeOwnerId, Module>>,
_not_send: PhantomData<*const ()>,
}
struct ActiveStreamCapture<'stream> {
stream: &'stream Stream,
finished: bool,
}
impl ActiveStreamCapture<'_> {
fn finish(mut self) -> Result<Graph> {
self.finished = true;
self.stream.end_capture()
}
fn discard(mut self) {
self.finished = true;
if let Err(error) = self.stream.end_capture() {
report_cleanup_failure("end", "cuda stream capture", &error);
}
}
}
impl Drop for ActiveStreamCapture<'_> {
fn drop(&mut self) {
if !self.finished
&& let Err(error) = self.stream.end_capture()
{
report_cleanup_failure("end", "cuda stream capture", &error);
}
}
}
impl Stream {
pub fn begin_capture(&self, mode: StreamCaptureMode) -> Result<()> {
let _lifecycle = self.allocation_guard()?;
self.inner.context.bind()?;
unsafe {
try_ffi!(runtime::cudaStreamBeginCapture(self.as_raw(), mode.into()))?;
}
Ok(())
}
pub unsafe fn begin_capture_to_graph(
&self,
graph: &Graph,
dependencies: &[GraphDependency],
mode: StreamCaptureMode,
) -> Result<()> {
let _lifecycle = self.allocation_guard()?;
self.check_graph_context(graph)?;
self.check_capture_dependency_contexts(dependencies)?;
Self::check_capture_graph_dependencies(graph, dependencies)?;
self.inner.context.bind()?;
let dependencies_raw: Vec<_> = dependencies
.iter()
.map(|dependency| dependency.node.as_raw())
.collect();
let edge_data_raw: Vec<_> = dependencies
.iter()
.map(|dependency| dependency.data.into())
.collect();
let count = dependencies_raw
.len()
.try_into()
.map_err(|_| Error::out_of_range("capture dependency count"))?;
unsafe {
try_ffi!(runtime::cudaStreamBeginCaptureToGraph(
self.as_raw(),
graph.as_raw(),
dependencies_raw.as_ptr(),
if edge_data_raw.is_empty() {
ptr::null()
} else {
edge_data_raw.as_ptr()
},
count,
mode.into(),
))?;
}
Ok(())
}
pub fn end_capture(&self) -> Result<Graph> {
self.inner.context.bind()?;
let mut handle = ptr::null_mut();
let mut cleanup = self.capture_cleanup_lock()?;
let result = unsafe {
try_ffi!(runtime::cudaStreamEndCapture(
self.as_raw(),
&raw mut handle
))
};
let ended =
result.is_ok() || matches!(self.capture_status(), Ok(StreamCaptureStatus::None));
let (released, cleanup_result) = if ended {
(
mem::take(&mut cleanup.owners),
cleanup.flush_frees(self.as_raw()),
)
} else {
(Vec::new(), Ok(()))
};
drop(cleanup);
drop(released);
result?;
let graph = unsafe { Graph::from_raw_in_context(handle, Arc::clone(&self.inner.context)) }?;
cleanup_result?;
Ok(graph)
}
pub fn capture<F>(&self, mode: StreamCaptureMode, f: F) -> Result<Graph>
where
F: FnOnce(&StreamCaptureScope<'_>) -> Result<()>,
{
self.begin_capture(mode)?;
let capture = ActiveStreamCapture {
stream: self,
finished: false,
};
let scope = StreamCaptureScope {
stream: self,
modules: RefCell::new(HashMap::new()),
_not_send: PhantomData,
};
let capture_result = panic::catch_unwind(panic::AssertUnwindSafe(|| f(&scope)));
match capture_result {
Ok(Ok(())) => {
let graph = capture.finish()?;
for module in scope.modules.into_inner().into_values() {
graph.retain_module(&module)?;
}
Ok(graph)
}
Ok(Err(error)) => {
capture.discard();
Err(error)
}
Err(payload) => {
drop(capture);
panic::resume_unwind(payload);
}
}
}
pub fn capture_executable<F>(
&self,
mode: StreamCaptureMode,
flags: GraphInstantiateFlags,
f: F,
) -> Result<ExecutableGraph>
where
F: FnOnce(&StreamCaptureScope<'_>) -> Result<()>,
{
let graph = self.capture(mode, f)?;
graph.instantiate(flags)
}
pub fn capture_status(&self) -> Result<StreamCaptureStatus> {
AsStream::capture_status(self)
}
pub fn capture_info(&self) -> Result<StreamCaptureInfo> {
self.inner.context.bind()?;
let mut status = runtime::cudaStreamCaptureStatus::CU_STREAM_CAPTURE_STATUS_NONE;
let mut id = 0;
unsafe {
try_ffi!(runtime::cudaStreamGetCaptureInfo(
self.as_raw(),
&raw mut status,
&raw mut id,
ptr::null_mut(),
ptr::null_mut(),
ptr::null_mut(),
ptr::null_mut(),
))?;
}
Ok(StreamCaptureInfo {
status: status.try_into()?,
id,
})
}
pub fn update_capture_dependencies(
&self,
dependencies: &[GraphDependency],
mode: StreamCaptureDependencyUpdate,
) -> Result<()> {
self.check_capture_dependency_contexts(dependencies)?;
self.check_active_capture_graph_dependencies(dependencies)?;
self.inner.context.bind()?;
let mut dependencies_raw: Vec<_> = dependencies
.iter()
.map(|dependency| dependency.node.as_raw())
.collect();
let edge_data_raw: Vec<_> = dependencies
.iter()
.map(|dependency| dependency.data.into())
.collect();
let count = dependencies_raw
.len()
.try_into()
.map_err(|_| Error::out_of_range("capture dependency count"))?;
unsafe {
try_ffi!(runtime::cudaStreamUpdateCaptureDependencies(
self.as_raw(),
dependencies_raw.as_mut_ptr(),
if edge_data_raw.is_empty() {
ptr::null()
} else {
edge_data_raw.as_ptr()
},
count,
mode.into(),
))?;
}
Ok(())
}
}
impl Stream {
fn check_graph_context(&self, graph: &Graph) -> Result<()> {
if graph.context() != &self.inner.context {
return Err(Error::context_mismatch("graph"));
}
Ok(())
}
fn check_capture_dependency_contexts(&self, dependencies: &[GraphDependency]) -> Result<()> {
for dependency in dependencies {
if matches!(dependency.node.context(), Some(context) if context != &self.inner.context)
{
return Err(Error::context_mismatch("graph dependency"));
}
}
Ok(())
}
fn check_capture_graph_dependencies(
graph: &Graph,
dependencies: &[GraphDependency],
) -> Result<()> {
for dependency in dependencies {
graph.check_node(&dependency.node)?;
}
Ok(())
}
fn check_active_capture_graph_dependencies(
&self,
dependencies: &[GraphDependency],
) -> Result<()> {
if dependencies.is_empty() {
return Ok(());
}
self.inner.context.bind()?;
let mut status = runtime::cudaStreamCaptureStatus::CU_STREAM_CAPTURE_STATUS_NONE;
let mut graph = ptr::null_mut();
unsafe {
try_ffi!(runtime::cudaStreamGetCaptureInfo(
self.as_raw(),
&raw mut status,
ptr::null_mut(),
&raw mut graph,
ptr::null_mut(),
ptr::null_mut(),
ptr::null_mut(),
))?;
}
if StreamCaptureStatus::try_from(status)? != StreamCaptureStatus::Active {
return Ok(());
}
if graph.is_null() {
return Err(Error::NullHandle);
}
for dependency in dependencies {
if !matches!(dependency.node.graph_raw(), Some(node_graph) if node_graph == graph) {
return Err(Error::GraphNodeMismatch);
}
}
Ok(())
}
pub fn ensure_not_capturing(&self) -> Result<()> {
AsStream::ensure_not_capturing(self)
}
}
impl<'scope> StreamCaptureScope<'scope> {
pub(crate) fn retain_module(&self, module: &Module) {
self.modules
.borrow_mut()
.entry(module.code_owner_id())
.or_insert_with(|| module.clone());
}
pub const fn stream(&self) -> &'scope Stream {
self.stream
}
}
pub fn exchange_capture_mode(mode: StreamCaptureMode) -> Result<StreamCaptureMode> {
let mut mode_raw: runtime::cudaStreamCaptureMode = mode.into();
unsafe {
try_ffi!(runtime::cudaThreadExchangeStreamCaptureMode(
&raw mut mode_raw
))?;
}
Ok(mode_raw.try_into()?)
}
impl_enum_display!(StreamCaptureStatus, {
StreamCaptureStatus::None => "CU_STREAM_CAPTURE_STATUS_NONE",
StreamCaptureStatus::Active => "CU_STREAM_CAPTURE_STATUS_ACTIVE",
StreamCaptureStatus::Invalidated => "CU_STREAM_CAPTURE_STATUS_INVALIDATED",
});
impl_enum_display!(StreamCaptureMode, {
StreamCaptureMode::Global => "CU_STREAM_CAPTURE_MODE_GLOBAL",
StreamCaptureMode::ThreadLocal => "CU_STREAM_CAPTURE_MODE_THREAD_LOCAL",
StreamCaptureMode::Relaxed => "CU_STREAM_CAPTURE_MODE_RELAXED",
});
impl_enum_display!(StreamCaptureDependencyUpdate, {
StreamCaptureDependencyUpdate::Add => "cudaStreamAddCaptureDependencies",
StreamCaptureDependencyUpdate::Set => "cudaStreamSetCaptureDependencies",
});