use crate::dtype::DType;
use crate::error::{Error, Result};
use crate::runtime::CapturedGraph;
use crate::runtime::cuda::client::CudaClient;
use crate::runtime::cuda::graph::CudaGraph;
use crate::runtime::cuda::runtime::CudaRuntime;
use crate::tensor::Tensor;
use super::session::CaptureSession;
pub(crate) fn capture_graph_into<F>(
client: &CudaClient,
inputs: &[&Tensor<CudaRuntime>],
outputs: &[&Tensor<CudaRuntime>],
f: F,
) -> Result<CapturedGraph<CudaRuntime>>
where
F: FnOnce(&CudaClient) -> Result<()>,
{
let owned_inputs: Vec<Tensor<CudaRuntime>> = inputs.iter().map(|t| (*t).clone()).collect();
let owned_outputs: Vec<Tensor<CudaRuntime>> = outputs.iter().map(|t| (*t).clone()).collect();
let session = CaptureSession::begin(&client.stream, &client.allocator, || Ok(()))?;
let closure_result = f(client);
let (graph_result, _) = session.end();
closure_result?;
let cudarc_graph = graph_result?.ok_or_else(|| {
Error::Backend(
"CUDA graph capture produced no operations — closure recorded nothing".into(),
)
})?;
Ok(CapturedGraph::new(
CudaGraph::new(cudarc_graph),
owned_inputs,
owned_outputs,
))
}
pub(crate) fn capture_graph_into_with_arena<F>(
client: &CudaClient,
inputs: &[&Tensor<CudaRuntime>],
outputs: &[&Tensor<CudaRuntime>],
arena_bytes: usize,
f: F,
) -> Result<CapturedGraph<CudaRuntime>>
where
F: FnOnce(&CudaClient) -> Result<()>,
{
let arena_elems = arena_bytes.div_ceil(std::mem::size_of::<f32>());
let arena_tensor = Tensor::<CudaRuntime>::empty(&[arena_elems], DType::F32, &client.device)
.map_err(|e| {
Error::Backend(format!(
"capture_graph_into_with_arena: arena allocation failed \
({arena_bytes} bytes): {e}"
))
})?;
let arena_ptr = arena_tensor.ptr();
let owned_inputs: Vec<Tensor<CudaRuntime>> = inputs.iter().map(|t| (*t).clone()).collect();
let owned_outputs: Vec<Tensor<CudaRuntime>> = outputs.iter().map(|t| (*t).clone()).collect();
let session = CaptureSession::begin(&client.stream, &client.allocator, || {
client.allocator.install_arena(arena_ptr, arena_bytes)
})?;
let closure_result = f(client);
let (graph_result, arena_bytes_used) = session.end();
closure_result?;
let cudarc_graph = graph_result?.ok_or_else(|| {
Error::Backend(
"CUDA graph capture (with_arena) produced no operations — \
closure recorded nothing"
.into(),
)
})?;
Ok(CapturedGraph::new_with_arena(
CudaGraph::new(cudarc_graph),
owned_inputs,
owned_outputs,
arena_tensor,
arena_bytes_used.unwrap_or(0),
))
}
#[cfg(test)]
mod tests {
use std::panic::AssertUnwindSafe;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::thread;
use crate::dtype::DType;
use crate::ops::BinaryOps;
use crate::runtime::Runtime;
use crate::runtime::common::Allocator;
use crate::runtime::cuda::{CudaClient, CudaDevice, CudaRuntime, is_cuda_available};
use crate::runtime::traits::client::RuntimeClient;
use crate::tensor::Tensor;
fn device_and_client() -> Option<(CudaDevice, CudaClient)> {
if !is_cuda_available() {
return None;
}
let device = CudaDevice::new(0);
let client = CudaRuntime::default_client(&device);
Some((device, client))
}
#[test]
fn capture_and_concurrent_work_both_produce_correct_results() {
let Some((device, client)) = device_and_client() else {
return;
};
let stop = Arc::new(AtomicBool::new(false));
let worker_stop = Arc::clone(&stop);
let worker_device = device.clone();
let worker_client = client.clone();
let worker = thread::spawn(move || -> bool {
let x =
Tensor::<CudaRuntime>::from_slice(&[1.0f32, 2.0, 3.0, 4.0], &[4], &worker_device)
.expect("worker input x");
let y = Tensor::<CudaRuntime>::from_slice(
&[10.0f32, 20.0, 30.0, 40.0],
&[4],
&worker_device,
)
.expect("worker input y");
let mut all_correct = true;
while !worker_stop.load(Ordering::Relaxed) {
let z = worker_client.add(&x, &y).expect("worker add");
worker_client.synchronize();
all_correct &= z.to_vec::<f32>() == vec![11.0, 22.0, 33.0, 44.0];
}
all_correct
});
let a = Tensor::<CudaRuntime>::from_slice(&[1.0f32, 2.0, 3.0, 4.0], &[4], &device)
.expect("capture input a");
let b = Tensor::<CudaRuntime>::from_slice(&[10.0f32, 20.0, 30.0, 40.0], &[4], &device)
.expect("capture input b");
let c = Tensor::<CudaRuntime>::zeros(&[4], DType::F32, &device).expect("capture output c");
for _ in 0..8 {
let captured = CudaRuntime::capture_graph_into(&client, &[&a, &b], &[&c], |cc| {
assert!(cc.is_capturing(), "capturing thread reports otherwise");
cc.add_into(&c, &a, &b)
})
.expect("capture_graph_into");
captured.launch().expect("graph launch");
client.synchronize();
assert_eq!(c.to_vec::<f32>(), vec![11.0, 22.0, 33.0, 44.0]);
}
stop.store(true, Ordering::Relaxed);
assert!(worker.join().expect("worker thread"), "worker got bad data");
}
#[test]
fn panic_in_capture_closure_leaves_device_usable() {
let Some((device, client)) = device_and_client() else {
return;
};
let a = Tensor::<CudaRuntime>::from_slice(&[1.0f32, 2.0, 3.0, 4.0], &[4], &device)
.expect("input a");
let b = Tensor::<CudaRuntime>::from_slice(&[10.0f32, 20.0, 30.0, 40.0], &[4], &device)
.expect("input b");
let c = Tensor::<CudaRuntime>::zeros(&[4], DType::F32, &device).expect("output c");
let unwound = std::panic::catch_unwind(AssertUnwindSafe(|| {
let _ = CudaRuntime::capture_graph_into(&client, &[&a, &b], &[&c], |cc| {
cc.add_into(&c, &a, &b)?;
panic!("capture closure failed");
});
}));
assert!(unwound.is_err(), "the closure's panic did not propagate");
assert!(!client.allocator.is_frozen(), "allocator left frozen");
assert!(!client.allocator.has_arena(), "arena left installed");
assert!(
!client.is_capturing(),
"thread still marked as capturing after unwind"
);
let captured = CudaRuntime::capture_graph_into(&client, &[&a, &b], &[&c], |cc| {
cc.add_into(&c, &a, &b)
})
.expect("capture after panic");
captured.launch().expect("graph launch after panic");
client.synchronize();
assert_eq!(c.to_vec::<f32>(), vec![11.0, 22.0, 33.0, 44.0]);
}
#[test]
fn concurrent_synchronize_waits_for_capture() {
let Some((device, client)) = device_and_client() else {
return;
};
let a = Tensor::<CudaRuntime>::from_slice(&[1.0f32, 2.0, 3.0, 4.0], &[4], &device)
.expect("input a");
let b = Tensor::<CudaRuntime>::from_slice(&[10.0f32, 20.0, 30.0, 40.0], &[4], &device)
.expect("input b");
let c = Tensor::<CudaRuntime>::zeros(&[4], DType::F32, &device).expect("output c");
let waiting = Arc::new(AtomicBool::new(false));
let synced = Arc::new(AtomicBool::new(false));
let worker_client = client.clone();
let worker_waiting = Arc::clone(&waiting);
let worker_synced = Arc::clone(&synced);
let worker = thread::spawn(move || {
worker_waiting.store(true, Ordering::SeqCst);
worker_client.synchronize();
worker_synced.store(true, Ordering::SeqCst);
});
let captured = CudaRuntime::capture_graph_into(&client, &[&a, &b], &[&c], |cc| {
cc.add_into(&c, &a, &b)?;
while !waiting.load(Ordering::SeqCst) {
thread::yield_now();
}
thread::sleep(std::time::Duration::from_millis(100));
assert!(
!synced.load(Ordering::SeqCst),
"a wait on the compute stream ran during capture"
);
Ok(())
})
.expect("capture_graph_into");
worker.join().expect("worker thread");
assert!(synced.load(Ordering::SeqCst), "the wait never completed");
captured.launch().expect("graph launch");
client.synchronize();
assert_eq!(c.to_vec::<f32>(), vec![11.0, 22.0, 33.0, 44.0]);
}
#[test]
fn capture_closure_launches_without_deadlocking() {
let Some((device, client)) = device_and_client() else {
return;
};
let a = Tensor::<CudaRuntime>::from_slice(&[1.0f32, 2.0, 3.0, 4.0], &[4], &device)
.expect("input a");
let b = Tensor::<CudaRuntime>::from_slice(&[1.0f32, 1.0, 1.0, 1.0], &[4], &device)
.expect("input b");
let c = Tensor::<CudaRuntime>::zeros(&[4], DType::F32, &device).expect("output c");
let captured = CudaRuntime::capture_graph_into(&client, &[&a, &b], &[&c], |cc| {
cc.add_into(&c, &a, &b)?;
for _ in 0..16 {
cc.add_into(&c, &c, &b)?;
}
Ok(())
})
.expect("capture with many launches");
captured.launch().expect("graph launch");
client.synchronize();
assert_eq!(c.to_vec::<f32>(), vec![18.0, 19.0, 20.0, 21.0]);
}
}