perf(serve): update the previous verifier's graph executables instead of instantiating anew

Each request's verifier instantiated its seven window/commit graphs again
(~19 ms of the ~110 ms assembly on the 5090, job 803 profile). A drained
verifier executable is now parked with its context (at most 16, destroyed
with the context) and the next verifier's graph of the same policy and node
count is applied to it with cuGraphExecUpdate; when the driver refuses the
update (topology or node kinds differ) the parked executable is destroyed
and the graph instantiated as before. LELEKA_GRAPH_EXEC_REUSE=off keeps the
per-request instantiation (A/B control).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Pavlo Ratushnyi
2026-10-16 19:45:42 +02:00
co-authored by Claude Opus 5.5
parent 57c2558961
commit 6fa92c13e4
3 changed files with 115 additions and 3 deletions
+22
View File
@@ -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, Rc<original_verify::abi::Module>, 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<Vec<original_gpu_schedule::ParkedExec>>,
}
#[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,
@@ -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<usize>,
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<usize> {
@@ -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<bool> = 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<abi::Api>,
}
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<abi::Api>) -> 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<usize> {
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)
}
}
@@ -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<bool> {
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<usize> {
Err(Error::UnsupportedPlatform)
}
pub(crate) fn exec_update(&self, _: usize, _: usize) -> Result<bool> {
Err(Error::UnsupportedPlatform)
}
pub(crate) fn graph_destroy(&self, _: usize) -> Result<()> {
Err(Error::UnsupportedPlatform)
}