diff --git a/crates/cuda-driver/src/lib.rs b/crates/cuda-driver/src/lib.rs index 873ccf25..b10edb07 100644 --- a/crates/cuda-driver/src/lib.rs +++ b/crates/cuda-driver/src/lib.rs @@ -416,6 +416,7 @@ impl<'driver> Device<'driver> { kar_levels: Cell::new(None), experimental: std::array::from_fn(|_| Cell::new(None)), window_modules: RefCell::new(Vec::new()), + parked_execs: RefCell::new(Vec::new()), }) } } @@ -467,6 +468,9 @@ pub struct Context<'driver> { /// Sealed verify-window modules loaded under this context, shared by every verifier bank created later /// (the serve path assembles one per request) and unloaded with the context. window_modules: RefCell, Vec<&'static str>)>>, + /// Drained verifier graph executables kept for the next verifier's graphs of the same shape (destroyed with + /// the context). + parked_execs: RefCell>, } #[derive(Clone, Copy)] struct FixedKernel { @@ -2086,6 +2090,22 @@ impl Context<'_> { } /// The shared verify-window modules: unloaded (current context) once no bank holds them; a module a live /// bank still shares is left to that bank's own unload. + fn destroy_parked_execs(&mut self) -> Result<()> { + let parked = std::mem::take(self.parked_execs.get_mut()); + if parked.is_empty() { + return Ok(()); + } + if self.is_poisoned() { + std::mem::forget(parked); + return Err(Error::ContextPoisoned); + } + let guard = self.enter()?; + let mut result = Ok(()); + for p in parked { + result = combine(result, p.api.exec_destroy(p.exec)); + } + combine(result, guard.finish()) + } fn unload_window_modules(&mut self) -> Result<()> { let modules = std::mem::take(self.window_modules.get_mut()); if modules.is_empty() { @@ -2150,6 +2170,7 @@ impl Context<'_> { let unload = combine(unload, self.unload_kar_levels()); let unload = combine(unload, self.unload_experimental()); let unload = combine(unload, self.unload_window_modules()); + let unload = combine(unload, self.destroy_parked_execs()); if let Some(handle) = self.handle.take() { // cuCtxDestroy accepts an owned non-current context. Pushing here // would add a stack entry for a handle invalidated by destruction. @@ -2611,6 +2632,7 @@ mod tests { kar_levels: Cell::new(None), experimental: std::array::from_fn(|_| Cell::new(None)), window_modules: RefCell::new(Vec::new()), + parked_execs: RefCell::new(Vec::new()), }; let make = |handle| DeviceBuffer { context: &context, diff --git a/crates/cuda-driver/src/original_gpu_schedule.rs b/crates/cuda-driver/src/original_gpu_schedule.rs index 5990bf2b..136ad214 100644 --- a/crates/cuda-driver/src/original_gpu_schedule.rs +++ b/crates/cuda-driver/src/original_gpu_schedule.rs @@ -309,6 +309,7 @@ impl<'ctx> OriginalGpuStream<'ctx> { nodes: None, policy, last_sequence: 0, + shape_nodes: 0, }; let begin = call(self.inner.context, &self.inner.api, |a| a.begin(h)); if let Err(primary) = begin { @@ -364,8 +365,30 @@ impl<'ctx> OriginalGpuStream<'ctx> { ); } } + // A verifier graph of an earlier (closed) verifier of this context with the same policy and node count is + // updated in place instead of instantiated again (cuGraphExecUpdate: the topology must match, else the driver + // refuses and the graph is instantiated as before). + let reusable = matches!(policy, OriginalCapturePolicy::VerifierWindow | OriginalCapturePolicy::VerifierCommit) + && reuse_execs(); + let parked = if reusable { + let n = call(g.context, &g.api, |a| a.nodes(graph))?; + g.shape_nodes = n; + g.context.take_parked_exec(policy as u8, n) + } else { + None + }; let instantiate = call(g.context, &g.api, |a| { - g.exec = Some(a.instantiate(graph)?); + g.exec = Some(match parked { + Some(e) => { + if a.exec_update(e, graph)? { + e + } else { + a.exec_destroy(e)?; + a.instantiate(graph)? + } + } + None => a.instantiate(graph)?, + }); if policy == OriginalCapturePolicy::Registry { g.done = Some(a.event_create(false)?); } else { @@ -589,6 +612,8 @@ pub struct OriginalGpuGraph<'ctx, R: OriginalGraphResources> { nodes: Option, policy: OriginalCapturePolicy, last_sequence: u64, + /// Node count of the captured graph of a reusable (verifier) policy: its executable's parking key. + shape_nodes: usize, } impl<'ctx, R: OriginalGraphResources> OriginalGpuGraph<'ctx, R> { fn validate(&self) -> Result { @@ -762,10 +787,20 @@ impl<'ctx, R: OriginalGraphResources> OriginalGpuGraph<'ctx, R> { if drained.is_err() { return drained; } - // Original reset order is executable -> graph -> completion event. + // Original reset order is executable -> graph -> completion event. A drained verifier executable is + // parked with the context for the next verifier's graph of the same shape (`capture_owned`). let mut result = Ok(()); if let Some(e) = self.exec.take() { - result = combine(result, a.exec_destroy(e)); + let park = matches!(self.policy, OriginalCapturePolicy::VerifierWindow | OriginalCapturePolicy::VerifierCommit) + && reuse_execs() + && self.graph.is_none(); + let parked = park + && self.shape_nodes > 0 + && !self.context.is_poisoned() + && self.context.park_exec(self.policy as u8, self.shape_nodes, e, Rc::clone(&self.api)); + if !parked { + result = combine(result, a.exec_destroy(e)); + } } if let Some(g) = self.graph.take() { result = combine(result, a.graph_destroy(g)); @@ -1045,3 +1080,32 @@ pub mod capture_timing { (v[0], v[1], v[2]) } } + +/// `LELEKA_GRAPH_EXEC_REUSE=off`: every verifier graph is instantiated anew (A/B control). +fn reuse_execs() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| !std::env::var("LELEKA_GRAPH_EXEC_REUSE").is_ok_and(|v| v == "off" || v == "0")) +} +/// A drained verifier executable kept by its context for the next verifier's graph of the same shape. +pub(crate) struct ParkedExec { + pub(crate) policy: u8, + pub(crate) nodes: usize, + pub(crate) exec: usize, + pub(crate) api: Rc, +} +impl<'d> Context<'d> { + /// Park `exec` (at most 16 per context); false when the caller must destroy it. + pub(crate) fn park_exec(&self, policy: u8, nodes: usize, exec: usize, api: Rc) -> bool { + let Ok(mut parked) = self.parked_execs.try_borrow_mut() else { return false }; + if parked.len() >= 16 || parked.try_reserve(1).is_err() { + return false; + } + parked.push(ParkedExec { policy, nodes, exec, api }); + true + } + pub(crate) fn take_parked_exec(&self, policy: u8, nodes: usize) -> Option { + let mut parked = self.parked_execs.try_borrow_mut().ok()?; + let at = parked.iter().position(|p| p.policy == policy && p.nodes == nodes)?; + Some(parked.swap_remove(at).exec) + } +} diff --git a/crates/cuda-driver/src/original_gpu_schedule_ffi.rs b/crates/cuda-driver/src/original_gpu_schedule_ffi.rs index fb3183f9..1767de7c 100644 --- a/crates/cuda-driver/src/original_gpu_schedule_ffi.rs +++ b/crates/cuda-driver/src/original_gpu_schedule_ffi.rs @@ -41,6 +41,14 @@ mod platform { type End = unsafe extern "C" fn(Handle, *mut Handle) -> i32; type Nodes = unsafe extern "C" fn(Handle, *mut Handle, *mut usize) -> i32; type Instantiate = unsafe extern "C" fn(*mut Handle, Handle, u64) -> i32; + /// `CUgraphExecUpdateResultInfo`. + #[repr(C)] + struct UpdateInfo { + result: i32, + error_node: Handle, + error_from_node: Handle, + } + type ExecUpdate = unsafe extern "C" fn(Handle, Handle, *mut UpdateInfo) -> i32; type GraphCall = unsafe extern "C" fn(Handle) -> i32; type GraphStream = unsafe extern "C" fn(Handle, Handle) -> i32; type CopyH2d = unsafe extern "C" fn(u64, *const c_void, usize, Handle) -> i32; @@ -78,6 +86,7 @@ mod platform { end: End, nodes: Nodes, instantiate: Instantiate, + exec_update: ExecUpdate, graph_destroy: GraphCall, exec_destroy: GraphCall, upload: GraphStream, @@ -125,6 +134,7 @@ mod platform { end: sym!(c"cuStreamEndCapture", End), nodes: sym!(c"cuGraphGetNodes", Nodes), instantiate: sym!(c"cuGraphInstantiateWithFlags", Instantiate), + exec_update: sym!(c"cuGraphExecUpdate_v2", ExecUpdate), graph_destroy: sym!(c"cuGraphDestroy", GraphCall), exec_destroy: sym!(c"cuGraphExecDestroy", GraphCall), upload: sym!(c"cuGraphUpload", GraphStream), @@ -245,6 +255,19 @@ mod platform { } Ok(e as usize) } + /// `cuGraphExecUpdate`: `Ok(true)` when the executable now runs `g`'s parameters, `Ok(false)` when the + /// driver refused the update (topology or node kind differ; the executable is unchanged and still valid). + pub(crate) fn exec_update(&self, e: usize, g: usize) -> Result { + let mut info = UpdateInfo { result: 0, error_node: std::ptr::null_mut(), error_from_node: std::ptr::null_mut() }; + // SAFETY: live executable and graph of the current context; `info` is a valid out-parameter. + let code = unsafe { (self.exec_update)(e as Handle, g as Handle, &mut info) }; + // CUDA_ERROR_GRAPH_EXEC_UPDATE_FAILURE (910): a refused update, not a fault. + match code { + 0 => Ok(info.result == 0), + 910 => Ok(false), + _ => check("cuGraphExecUpdate", code).map(|()| false), + } + } pub(crate) fn graph_destroy(&self, g: usize) -> Result<()> { check("cuGraphDestroy", unsafe { (self.graph_destroy)(g as Handle) @@ -359,6 +382,9 @@ impl Api { pub(crate) fn instantiate(&self, _: usize) -> Result { Err(Error::UnsupportedPlatform) } + pub(crate) fn exec_update(&self, _: usize, _: usize) -> Result { + Err(Error::UnsupportedPlatform) + } pub(crate) fn graph_destroy(&self, _: usize) -> Result<()> { Err(Error::UnsupportedPlatform) }